package com.hsmpay.mobile.action.user;

import com.hsmpay.common.pojo.BasePojo;
import com.hsmpay.common.pojo.user.Loan;
import com.hsmpay.common.pojo.user.User;
import com.hsmpay.common.util.ClearMac;
import com.hsmpay.common.util.MD5;
import com.hsmpay.common.util.NumberUtil;
import com.hsmpay.common.util.ThreeMaoBankUtil;
import com.hsmpay.common.util.bank.BankCardTypeUtil;
import com.hsmpay.mobile.action.account.officialAccPay.OfficialAccPayBaseAction;
import com.hsmpay.mobile.action.base.MobileBaseAction;
import com.hsmpay.mobile.pojo.bank.Bank;
import com.hsmpay.mobile.pojo.bank.BankBranches;
import com.hsmpay.mobile.pojo.bank.BankCode;
import com.hsmpay.mobile.pojo.device.DeviceKey;
import com.hsmpay.mobile.pojo.message.LoginMessage;
import com.hsmpay.mobile.pojo.other.Settings;
import com.hsmpay.mobile.pojo.system.SystemData;
import com.hsmpay.mobile.pojo.terminal.TerminalType;
import com.hsmpay.mobile.pojo.trans.SSBindCards;
import com.hsmpay.mobile.pojo.trans.SSBindCardsExample;
import com.hsmpay.mobile.pojo.trans.UserNocardpayLog;
import com.hsmpay.mobile.pojo.trans.UserVerifycardsLog;
import com.hsmpay.mobile.pojo.trans.cardcer.CardCer;
import com.hsmpay.mobile.pojo.user.*;
import com.hsmpay.mobile.service.bank.BankBranchesService;
import com.hsmpay.mobile.service.bank.BankCodeService;
import com.hsmpay.mobile.service.bank.BankService;
import com.hsmpay.mobile.service.device.DeviceKeyService;
import com.hsmpay.mobile.service.message.LoginMessageService;
import com.hsmpay.mobile.service.other.SettingsService;
import com.hsmpay.mobile.service.system.SystemDataService;
import com.hsmpay.mobile.service.terminal.TerminalTypeService;
import com.hsmpay.mobile.service.trans.SSBindCardsService;
import com.hsmpay.mobile.service.trans.cardcer.CardCerService;
import com.hsmpay.mobile.service.user.*;
import com.hsmpay.mobile.util.RegularUtils;
import com.hsmpay.utils.*;
import com.hsmpay.utils.system.ConConfig;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;


/**
 * 手机端用户action
 *
 * @author 颜铃璋
 * @date 2012-12-14
 */
@Controller("userAction")
@Scope("prototype")
@SuppressWarnings("unused")
public class UserAction extends MobileBaseAction {
    private static final long serialVersionUID = 1L;
    private static Logger log = LoggerFactory.getLogger(UserAction.class);
    public static final String SESSION_USER = "SESSION_USER";
    private String action;
    private String activationCode;//激活码
    private String loginName;//登录名称
    private String password;//密码
    private String nickName;//昵称（需要DEncoder转码）
    private String mobile;//手机号码
    private String email;//邮件

    private String bankCard;//银行卡
    private String identityCard;//身份证
    private String openingBank;//开户行
    private Integer bBankProvince;//支行所在省
    private Integer bBankCity;//支行所在市
    private String branchesBank;//支行名称
    private Long branchesBankId;//支行ID
    private String userName;//真实姓名
    private String code;//验证码
    private Integer loginType;//登录方式
    private String oldPassword;//原密码
    private Integer type;//类型
    private String payPassword;//支付密码
    private String oldPayPassword;//原支付密码
    private String oldBankCard;//旧的
    private Integer machineType;//终端机器类型
    private String uuId;//终端机器唯一标识
    private Integer crashT1Type;//T+1 提现
    private Integer verifiType;//验证类型 0、不需要验证 1、手机验证码验证 2、支付密码验证
    private String codeOrPswd;//验证码或支付密码
    private String deviceId;//设备编号

    private User user;
    private String lat;
    private String lng;
    private String x;
    private String y;
    //经营范围ID与经营地址
    private Long businessRangeId;
    private String businessAddress;
    //唯一标识 安卓值为唯一标识  iphone 为token
    private String uniqueId;
    //贷款信息
    private Loan loan;

    public String urlStr = ConConfig.getAttribute("URL_OFFICIAL");
    public String appid = ConConfig.getAttribute("WEIXIN_APPID");
    public String secret = ConConfig.getAttribute("WEIXIN_SECRET");
    public String getCodeUrl = ConConfig.getAttribute("WEIXIN_GET_CODE_URL");

    @Resource(name = "activationCodeService")
    private ActivationCodeService<ActivationCode, Long> activationCodeService;//激活码服务类
    @Resource(name = "registerCodeService")
    private RegisterCodeService<BasePojo, Long> registerCodeService;//注册激活码服务类
    @Resource(name = "bankBranchesService")
    private BankBranchesService<BankBranches, Long> bankBranchesService;
    @Resource(name = "bindingBankCardLogService")
    private BindingBankCardLogService<BindingBankCardLog, Long> bindingBankCardLogService;//绑定银行卡
    @Resource(name = "systemDataService")
    private SystemDataService<SystemData, Long> systemDataService;//经营范围服务类
    @Resource(name = "loginMessageService")
    private LoginMessageService<LoginMessage, Long> loginMessageService;//登录消息
    @Resource(name = "userDPIService")
    private UserDPIService<UserDPI, Long> userDPIService;//实名认证
    @Resource(name = "verifiService")
    private VerifiService<BasePojo, Long> verifiService;//手机验证码 验证
    @Resource(name = "deviceKeyService")
    private DeviceKeyService<DeviceKey, Long> deviceKeyService;//设备秘钥信息
    @Resource(name = "settingsService")
    protected SettingsService<Settings, Long> settingsService;
    @Resource(name = "ssBindCardsService")
    private SSBindCardsService<SSBindCards, Long> bindCardsService; // 秒到业务

    @Resource(name = "cardCerService")
    private CardCerService<CardCer, Long> cardCerService;
    @Resource(name = "bankCodeService")
    public BankCodeService<BankCode, Long> bankCodeService;
    @Resource(name = "sendmsgLogService")
    private SendmsgLogService<SendmsgLog, Long> sendmsgLogService;
    @Resource(name = "bankService")
    private BankService<Bank, Long> bankService;
    @Resource(name = "userMoneyService")
    private UserMoneyService<UserMoney, Long> userMoneyService;
    @Resource(name = "terminalTypeService")
    private TerminalTypeService<TerminalType, Long> terminalTypeService;
    @Resource(name = "loanService")
    private LoanService<Loan,Long> loanService;//贷款类


    /**
     * 注册时 获取经营范围列表
     *
     * @throws Exception
     */
    public void getBusinessRangeList() throws Exception {
        try {
            log.debug("********** 获取经营范围列表 开始 ***************");
            List<SystemData> systemDataList = systemDataService.getSystemDataList("经营范围");

            Map<String, Object> result = new LinkedHashMap<String, Object>();
            result.put("reqCode", "0000");
            result.put("reqMsg", "可以通过注册下一步！");
            result.put("businessRangeList", systemDataList);
            sendAppMsg(result);
            systemDataList = null;//集合应该释放 内存
            result = null;
        } catch (Exception e) {
            sendAjaxResponse("-1");
            e.printStackTrace();
            throw e;
        } finally {
            log.debug("********** 获取经营范围列表 结束 ***************");
        }
    }

    /**
     * 用户注册 下一步
     *
     * @return
     * @throws Exception
     */
    public String firstNextBnRegister() throws Exception {
        JSONObject js = JSONObject.fromObject(getRequest().getAttribute(FC_DATA));
        action = js.getString("action");
        clientType = Integer.parseInt(js.getString("clientType"));
        terminalTypeId = Long.parseLong(js.getString("terminalTypeId"));
        roleId = Long.parseLong(js.getString("roleId"));

        if (js.containsKey("activationCode"))
            activationCode = js.getString("activationCode");
        if (js.containsKey("mobile"))
            mobile = js.getString("mobile").trim();

        log.debug("action = " + action);
        log.debug("clientType = " + clientType);
        log.debug("terminalTypeId = " + terminalTypeId);
        log.debug("roleId = " + roleId);
        log.debug("activationCode = " + activationCode);
        log.debug("mobile = " + mobile);

        if (StringUtils.isBlank(activationCode)) {
            log.warn("用户注册时, 传入参数activationCode为空");
            sendAppErrorMsg("6001", "activationCode");
            return null;
        }
        if (StringUtils.isBlank(mobile)) {
            log.warn("用户注册时, 传入参数mobile为空");
            sendAppErrorMsg("6001", "mobile");
            return null;
        }

        try {
            mobile = mobile.trim();
            user = new User();
            user.setMobile(mobile);
            user = userService.searchEntity(user);
            if (null != user) {
                log.warn("用户注册点击第一个下一步按钮时, 手机已经注册！");
                sendAppErrorMsg("6003");
                return null;
            }

            //验证注册激活码
            ActivationCode activationCodeBean = activationCodeService.searchACodeToRegister(activationCode, terminalTypeId, roleId);
            if (null == activationCodeBean) {
                log.warn("用户注册点击第一个下一步按钮时, 注册激活码输入错误！");
                sendAppErrorMsg("6009");
                return null;
            }

            log.debug("用户注册点击第一个下一步按钮时, 校验数据成功！");
            Map<String, Object> result = new LinkedHashMap<String, Object>();
            result.put("reqCode", "0000");
            result.put("reqMsg", "可以通过注册下一步！");
            sendAppMsg(result);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            log.debug("--- firstNextBnRegister() end ---");
        }
        return null;
    }

    /**
     * 用户注册
     *
     * @return
     * @throws Exception
     */
    public String register() throws Exception {
        log.debug("--- register() start ---");
        JSONObject js = JSONObject.fromObject(getRequest().getAttribute(FC_DATA));
        action = js.getString("action");
        clientType = Integer.parseInt(js.getString("clientType"));
        terminalTypeId = Long.parseLong(js.getString("terminalTypeId"));
        roleId = Long.parseLong(js.getString("roleId"));

        if (js.containsKey("activationCode"))
            activationCode = js.getString("activationCode");
        if (js.containsKey("mobile"))
            mobile = js.getString("mobile").trim();
        if (js.containsKey("password"))
            password = js.getString("password");
        if (js.containsKey("businessRangeId"))
            businessRangeId = Long.parseLong(js.getString("businessRangeId"));
        if (js.containsKey("businessAddress"))
            businessAddress = js.getString("businessAddress");
        if (js.containsKey("verifiType"))
            verifiType = Integer.parseInt(js.getString("verifiType"));
        if (js.containsKey("codeOrPswd"))
            codeOrPswd = js.getString("codeOrPswd");

        log.debug("action = " + action);
        log.debug("clientType = " + clientType);
        log.debug("terminalTypeId = " + terminalTypeId);
        log.debug("roleId = " + roleId);
        log.debug("activationCode = " + activationCode);
        log.debug("mobile = " + mobile);
        log.debug("password = " + password);
        log.debug("businessRangeId = " + businessRangeId);//经营范围ID 必填
        log.debug("businessAddress = " + businessAddress);//经营地址 必填

        if (StringUtils.isBlank(activationCode)) {
            log.warn("用户注册时, 传入参数activationCode为空");
            sendAppErrorMsg("6001", "activationCode");
            return null;
        }
        if (StringUtils.isBlank(mobile)) {
            log.warn("用户注册时, 传入参数mobile为空");
            sendAppErrorMsg("6001", "mobile");
            return null;
        }
        if (!RegularUtils.checkMobile(mobile)) {
            log.warn("用户注册时, 手机号格式错误");
            sendAppErrorMsg("6102");
            return null;
        }
        if (StringUtils.isBlank(password)) {
            log.warn("用户注册时, 传入参数password为空");
            sendAppErrorMsg("6001", "password");
            return null;
        }
        if (null == businessRangeId) {
            log.warn("用户注册时, 传入参数businessRangeId为空");
            sendAppErrorMsg("6001", "businessRangeId");
            return null;
        }
        if (StringUtils.isBlank(businessAddress)) {
            log.warn("用户注册时, 传入参数businessAddress为空");
            sendAppErrorMsg("6001", "businessAddress");
            return null;
        }
        if (null != verifiType && verifiType != 0) {
            if (null == codeOrPswd) {
                log.warn("用户注册时, 传入参数codeOrPswd为空");
                sendAppErrorMsg("6001", "codeOrPswd");
                return null;
            }
        }
        try {
            if (terminalTypeId.intValue() == 10) {//###########################品亿通默认登录全部都是全版
                roleId = 1l;
            }

            mobile = mobile.trim();
            password = password.trim();

            user = new User();
            user.setMobile(mobile);
            user.setRoleId(roleId);
            user.setTerminalTypeId(terminalTypeId);
            user = userService.searchEntity(user);
            if (null != user) {
                log.warn("注册时, 手机已经注册！");
                sendAppErrorMsg("6003", mobile);
                return null;
            }

            //查询激活码对象
            ActivationHistory activationHistory = null;
            ActivationCode activationCodeBean = null;
            if (null != bankCard) {
                bankCard = bankCard.trim();
            }
            activationCodeBean = activationCodeService.searchACodeToRegister(activationCode, terminalTypeId, roleId);
            if (null == activationCodeBean) {
                sendAppErrorMsg("6009");
                return null;
            } else {
                if (1 == activationCodeBean.getIsActivation().intValue()) {
                    sendAppErrorMsg("6013");
                    return null;
                }
            }
            //组装激活码用户注册历史记录对象
            activationHistory = new ActivationHistory();
            activationHistory.setCodeId(activationCodeBean.getId());
            activationHistory.setLat(lat);
            activationHistory.setLng(lng);
            activationHistory.setY(y);
            activationHistory.setX(x);

            //验证 手机验证码
            boolean verifi = verifiService.verifiCode(VerifiService.CODETYPE_REGISTER, verifiType, codeOrPswd, mobile, null);
            if (!verifi) {
                log.warn("注册时, 验证失败！");
                sendAppErrorMsg("6014");
                return null;
            }

            user = new User();
            user.setTerminalTypeId(terminalTypeId);
            user.setRoleId(roleId);
            user.setClientType(clientType);
            user.setLoginName(mobile);//注意 用户名 改为
            user.setMobile(mobile);
            password = MD5.mD5ofStr(password);
            log.debug("md5 password = " + password);
            user.setPassword(password);
            user.setBankStatus(3);//默认  未认证
            user.setRoleType(1);
            user.setActive(1);
            //添加费率
            if (null != activationCodeBean) {
                user.setOrganizationId(activationCodeBean.getOrganizationId());//机构ID
                user.setFeeRate(activationCodeBean.getFeeRate());//手续费费率
                user.setClearRate(activationCodeBean.getClearRate());//结算费率
                user.setOwnBrokerageRate(activationCodeBean.getOwnBrokerageRate());//佣金比例
                user.setActivationCode(activationCode);//激活码
                user.setRoleId(activationCodeBean.getRoleId());
                user.setClearFee(activationCodeBean.getClearFee());
                user.setFdMaxFee(activationCodeBean.getFdMaxFee());
                user.setFdMinFee(activationCodeBean.getFdMinFee());
                user.setCashRate(null == activationCodeBean.getCashRate() ? 0.002 : activationCodeBean.getCashRate());//提现费率
                user.setFdFeeRate(activationCodeBean.getFdFeeRate());
            }
            //添加经营范围
            user.setBusinessRangeId(businessRangeId);
            user.setBusinessAddress(businessAddress);
            long channelId = Long.valueOf(settingsService.getMainValueByFk("MOBILE_REGISTER_DEFAULT_CHANNEL"));
            user.setChannelId(channelId);//默认 收款通道 DEFAULT_CHANNELID
            user.setMachineType(0);//默认 没有绑定终端
            user.setCrashT1Type(0);//系统T+1提现  模式  默认
            userId = userService.register(user, activationHistory);
            if (null != userId && userId > 0l) {
                Map<String, Object> result = new LinkedHashMap<String, Object>();
                result.put("userId", userId);
                result.put("reqCode", "0000");
                result.put("reqMsg", "注册成功！");
                log.debug("注册成功！");//userId.toString()
                sendAppMsg(result);
            } else {
                log.warn("注册失败！");
                sendAppErrorMsg("9999");//未知错误
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            log.debug("--- register() end ---");
        }
    }

    /**
     * 绑定银行卡号
     *
     * @return
     * @throws Exception
     */
    public String bindingBankCard() throws Exception {
        log.debug("--- bindingBankCard() start ---");
        JSONObject js = JSONObject.fromObject(getRequest().getAttribute(FC_DATA));
        action = js.getString("action");
        clientType = Integer.parseInt(js.getString("clientType"));
        terminalTypeId = Long.parseLong(js.getString("terminalTypeId"));
        roleId = Long.parseLong(js.getString("roleId"));

        if (js.containsKey("userId"))
            userId = Long.parseLong(js.getString("userId"));
        if (js.containsKey("bankCard"))
            bankCard = js.getString("bankCard").trim();
        if (js.containsKey("userName"))
            userName = js.getString("userName").trim();
        if (js.containsKey("openingBank"))
            openingBank = js.getString("openingBank");
        if (js.containsKey("bBankProvince"))
            bBankProvince = Integer.parseInt(js.getString("bBankProvince"));
        if (js.containsKey("bBankCity"))
            bBankCity = Integer.parseInt(js.getString("bBankCity"));
        if (js.containsKey("branchesBankId"))
            branchesBankId = Long.parseLong(js.getString("branchesBankId"));

        log.debug("userId = " + userId);
        log.debug("bankCard = " + bankCard);
        log.debug("userName = " + userName);
        log.debug("openingBank = " + openingBank);
        log.debug("bBankProvince = " + bBankProvince);
        log.debug("bBankCity = " + bBankCity);
        log.debug("branchesBankId = " + branchesBankId);//用户可选

        if (null == userId) {
            log.warn("绑定银行卡号时, 传入参数userId为空");
            sendAppErrorMsg("6001", "userId");
            return null;
        }
        if (StringUtils.isBlank(bankCard)) {
            log.warn("绑定银行卡号时, 传入参数bankCard为空");
            sendAppErrorMsg("6001", "bankCard");
            return null;
        }
        if(BankCardTypeUtil.isCreditCard(bankCard)){
            log.warn("绑定银行卡时, 只能绑定储蓄卡!");
            sendAppErrorMsg("6122");
            return null;
        }
        if (StringUtils.isBlank(openingBank)) {
            log.warn("绑定银行卡号时, 传入参数openingBank为空");
            sendAppErrorMsg("6001", "openingBank");
            return null;
        }
        if (StringUtils.isBlank(userName)) {
            log.warn("绑定银行卡号时, 传入参数userName为空");
            sendAppErrorMsg("6001", "userName");
            return null;
        }
        if (null == bBankProvince) {
            log.warn("绑定银行卡号时, 传入参数bBankProvince为空");
            sendAppErrorMsg("6001", "bBankProvince");
            return null;
        }
        if (null == bBankCity) {
            log.warn("绑定银行卡号时, 传入参数bBankCity为空");
            sendAppErrorMsg("6001", "bBankCity");
            return null;
        }
        if (null == branchesBankId) {
            log.warn("绑定银行卡号时, 传入参数branchesBankId为空");
            sendAppErrorMsg("6001", "branchesBankId");
            return null;
        }
        try {
            bankCard = bankCard.trim();
            userName = userName.trim();
            user = userService.getUserById(userId);

            user.setBankCard(bankCard);
            user.setOpeningBank(openingBank);
            user.setBBankProvince(bBankProvince);
            user.setBBankCity(bBankCity);
            user.setClearMac(ClearMac.getUserClearMac(user.getLoginName(), user.getIdentityCard(), bankCard, openingBank, user.getCardholder()));//验证

            if (null != branchesBankId) {
                BankBranches bankB = bankBranchesService.searchBankBranchesById(branchesBankId);
                if (null != bankB) {
                    user.setBranchesBank(bankB.getName());
                    user.setBranchesBankCode(bankB.getCode());
                    user.setAccBankCode(ThreeMaoBankUtil.getCode(bankB.getBankId()));//三毛银行 代码
                } else {
                    log.debug("支行Id传入错误！");//userId.toString()
                    sendAppErrorMsg("9999");
                }
            }
            int flag = userService.bindingBankCard(user);
            Map<String, Object> result = new LinkedHashMap<String, Object>();
            if (flag > 0) {
                log.warn("绑定银行卡号成功！");
                result.put("reqCode", "0000");
                //result.put("status", 1);
                result.put("reqMsg", "绑定银行卡号成功！！");
                sendAppMsg(result);
            } else {
                log.warn("绑定银行卡号失败！");
                sendAppErrorMsg("9999");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            log.debug("--- bindingBankCard() end ---");
        }
        return null;
    }

    /**
     * 修改银行卡
     *
     * @return
     * @throws Exception
     */
    public String updateBindingBankCard() throws Exception {
        log.debug("--- updateBindingBankCard() start ---");
        clientType = Integer.parseInt(getJsonString("clientType"));
        terminalTypeId = Long.parseLong(getJsonString("terminalTypeId"));
        roleId = Long.parseLong(getJsonString("roleId"));
        if (null != getJsonString("userId"))
            userId = Long.parseLong(getJsonString("userId"));
        bankCard = getJsonString("bankCard");
        oldBankCard = getJsonString("oldBankCard");
        openingBank = getJsonString("openingBank");
        if (null != getJsonString("bBankProvince"))
            bBankProvince = Integer.parseInt(getJsonString("bBankProvince"));
        if (null != getJsonString("bBankCity"))
            bBankCity = Integer.parseInt(getJsonString("bBankCity"));
        if (null != getJsonString("branchesBankId"))
            branchesBankId = Long.parseLong(getJsonString("branchesBankId"));
        if (StringUtils.isNotEmpty(getJsonString("verifiType")))
            verifiType = Integer.parseInt(getJsonString("verifiType"));
        if (StringUtils.isNotEmpty(getJsonString("codeOrPswd")))
            codeOrPswd = getJsonString("codeOrPswd");


        if (null == userId) {
            log.warn("修改银行卡时, 传入参数userId为空");
            sendAppErrorMsg("6001", "userId");
            return null;
        }
        if (StringUtils.isBlank(bankCard)) {
            log.warn("修改银行卡时, 传入参数bankCard为空");
            sendAppErrorMsg("6001", "bankCard");
            return null;
        }
        if (BankCardTypeUtil.isCreditCard(bankCard)) {
            log.warn("修改银行卡时, 只能绑定储蓄卡!");
            sendAppErrorMsg("6122");
            return null;
        }
        if (StringUtils.isBlank(oldBankCard)) {
            log.warn("修改银行卡时, 传入参数oldBankCard为空");
            sendAppErrorMsg("6001", "oldBankCard");
            return null;
        }
        if (StringUtils.isBlank(openingBank)) {
            log.warn("修改银行卡时, 传入参数openingBank为空");
            sendAppErrorMsg("6001", "openingBank");
            return null;
        }
        if (null == bBankProvince) {
            log.warn("修改银行卡时, 传入参数bBankProvince为空");
            sendAppErrorMsg("6001", "bBankProvince");
            return null;
        }
        if (null == bBankCity) {
            log.warn("修改银行卡时, 传入参数bBankCity为空");
            sendAppErrorMsg("6001", "bBankCity");
            return null;
        }
        if (null == branchesBankId) {
            log.warn("修改银行卡时, 传入参数branchesBankId为空");
            sendAppErrorMsg("6001", "branchesBankId");
            return null;
        }
        if (null != verifiType && verifiType != 0) {
            if (null == codeOrPswd) {
                log.warn("用户注册时, 传入参数codeOrPswd为空");
                sendAppErrorMsg("6001", "codeOrPswd");
                return null;
            }
        }
        try {
            bankCard = bankCard.trim();
            oldBankCard = oldBankCard.trim();
            user = userService.getUserById(userId);

            if (oldBankCard.equals(bankCard)) {
                log.warn("修改银行卡时, 原绑定卡号输入错误！");
                sendAppErrorMsg("6044");
                return null;
            }

            User quser = userService.getUserById(userId);
            if (!oldBankCard.equals(quser.getBankCard())) {
                log.warn("修改银行卡时, 原绑定卡号输入错误！");
                sendAppErrorMsg("6045");
                return null;
            }

            //验证 手机验证码
            boolean verifi = verifiService.verifiCode(VerifiService.CODETYPE_UPBBANKCARD, verifiType, codeOrPswd, user.getMobile(), null);
            if (!verifi) {
                log.warn("注册时, 验证失败！");
                sendAppErrorMsg("6014");
                return null;
            }

            user.setBankCard(bankCard);
            user.setOpeningBank(openingBank);
            //user.setCardholder(userName);
            user.setBBankProvince(bBankProvince);
            user.setBBankCity(bBankCity);
            user.setClearMac(ClearMac.getUserClearMac(user.getLoginName(), user.getIdentityCard(), bankCard, openingBank, user.getCardholder()));//验证

            if (null != branchesBankId) {
                BankBranches bankB = bankBranchesService.searchBankBranchesById(branchesBankId);
                if (null != bankB) {
                    user.setBranchesBank(bankB.getName());
                    user.setBranchesBankCode(bankB.getCode());
                    user.setAccBankCode(ThreeMaoBankUtil.getCode(bankB.getBankId()));//三毛银行 代码
                } else {
                    log.debug("支行Id传入错误！");//userId.toString()
                    sendAppErrorMsg("9999");
                }
            }

            int flag = userService.bindingBankCard(user);

            Map<String, Object> result = new LinkedHashMap<String, Object>();
            if (flag > 0) {

                //修改用户报备状态 0未报备 1已报备 2修改绑定银行卡后未更新报备 为了避免memcache缓存干扰 直接从库里读取数据
                User dbUser = new User();
                dbUser.setId(userId);
                dbUser = userService.searchEntity(dbUser);
                int isReport = dbUser.getIsReport();
                if (isReport == 1) {
                    dbUser.setIsReport(2);
                    userService.updateEntity(dbUser);
                }

                log.warn("修改绑定银行卡号成功！");
                result.put("reqCode", "0000");
                result.put("reqMsg", "修改绑定银行卡号成功！！");
                sendAppMsg(result);
            } else {
                log.warn("修改绑定银行卡号失败！");
                sendAppErrorMsg("9999");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            log.debug("--- updateBindingBankCard() end ---");
        }
        return null;
    }

    /**
     * 用户登录
     *
     * @return
     * @throws Exception
     */
    public String login() throws Exception {
        log.debug("--- login() start ---");

        JSONObject js = JSONObject.fromObject(getRequest().getAttribute(FC_DATA));
        action = js.getString("action");
        clientType = Integer.parseInt(js.getString("clientType"));
        terminalTypeId = Long.parseLong(js.getString("terminalTypeId"));
        roleId = Long.parseLong(js.getString("roleId"));

        if (js.containsKey("uniqueId"))
            uniqueId = js.getString("uniqueId");
        if (js.containsKey("loginType"))
            loginType = Integer.parseInt(js.getString("loginType"));
        if (js.containsKey("mobile"))
            mobile = js.getString("mobile");
        if (js.containsKey("password"))
            password = js.getString("password");
        if (js.containsKey("bankCard"))
            bankCard = js.getString("bankCard");
        log.debug("action = " + action);
        log.debug("clientType = " + clientType);
        log.debug("terminalTypeId = " + terminalTypeId);
        log.debug("roleId = " + roleId);
        log.debug("uniqueId = " + uniqueId);
        log.debug("loginType = " + loginType);
        log.debug("mobile = " + mobile);
        log.debug("password = " + password);
        log.debug("bankCard = " + bankCard);

        if (null == loginType) {
            log.warn("用户登录时, 传入参数loginType为空");
            sendAppErrorMsg("6001", "loginType");
            return null;
        }
        if (StringUtils.isBlank(mobile)) {
            log.warn("用户登录时, 传入参数mobile为空");
            sendAppErrorMsg("6001", "mobile");
            return null;
        }
        if (!RegularUtils.checkMobile(mobile)) {
            log.warn("用户登录时, 手机号格式错误");
            sendAppErrorMsg("6102");
            return null;
        }
        if (1 == loginType.intValue()) {
            if (StringUtils.isBlank(password)) {
                log.warn("用户登录时, 传入参数password为空");
                sendAppErrorMsg("6001", "password");
                return null;
            }
            password = password.trim();
        } else {
            if (StringUtils.isBlank(bankCard)) {
                log.warn("用户登录时, 传入参数bankCard为空");
                sendAppErrorMsg("6001", "bankCard");
                return null;
            }
        }
        try {
            if (terminalTypeId.intValue() == 10) {//########################### 品亿通默认登录全部都是全版
                roleId = 1l;
            }

            mobile = mobile.trim();
            user = new User();
            user.setMobile(mobile);
            user.setRoleId(roleId);
            user.setTerminalTypeId(terminalTypeId);
            user = userService.searchEntity(user);

            boolean isZhongyi = false;
            if (null == user) {//判断是否是  花生米 的特殊账户
                user = new User();
                user.setTerminalTypeId(null);
                user.setOrganizationId(1l);
                user.setRoleId(1l);
                user.setMobile(mobile);
                user = userService.searchEntity(user);
                isZhongyi = true;

            }

            if (null != user) {
                if (!isZhongyi && null != terminalTypeId && (null == user.getTerminalTypeId() || !user.getTerminalTypeId().equals(terminalTypeId))) {//不是一个终端 提示为用户不存在
                    if (1 == loginType.intValue()) {
                        log.warn("登录时，用户名不存在！");//不是一个终端
                        sendAppErrorMsg("6008");
                    } else {//手机号+银行卡号 登录
                        log.warn("登录时，卡号没有被用户绑定！！");//不是一个终端
                        sendAppErrorMsg("6007");
                    }
                    return null;
                }
                if (1 == loginType.intValue()) {//手机号+密码 登录
                    user.setMobile(mobile);
                    password = MD5.mD5ofStr(password);
                    log.debug("md5密码：" + password);
                    user.setPassword(password);
                } else {//手机号+银行卡号 登录
                    user.setBankCard(bankCard);
                }
                user = userService.searchEntity(user);
                if (null != user) {
                    if (1 == user.getDeleted().intValue()) {
                        log.warn("登录时，该用户已暂停使用！");
                        sendAppErrorMsg("6004");
                        return null;
                    } else if (2 == user.getDeleted().intValue()) {
                        log.warn("登录时，该用户已被注销！");
                        sendAppErrorMsg("6005");
                        return null;
                    }

                    Map<String, Object> result = new LinkedHashMap<String, Object>();
                    result.put("userId", user.getId());
                    result.put("mobile", user.getMobile());
                    result.put("bankCard", null != user.getBankCard() ? user.getBankCard() : "");
                    result.put("identityCard", null != user.getIdentityCard() ? user.getIdentityCard() : "");
                    result.put("openingBank", null != user.getOpeningBank() ? user.getOpeningBank() : "");
                    result.put("userName", null != user.getUserName() ? user.getUserName() : "");

                    //实名认证错误信息
                    result.put("dPIStatus", (null == user.getDPIStatus() || 4 == user.getDPIStatus().intValue()) ? 3 : user.getDPIStatus());//4重置暂时改为3
                    if ((null == user.getUserName() || user.getUserName().indexOf("null") != -1) && !(null == user.getDPIStatus() || 3 == user.getDPIStatus().intValue()))//如果用户名为空 那么实名认证不通过
                        result.put("dPIStatus", 0);
                    if (null != user.getDPIStatus() && 0 == user.getDPIStatus().intValue()) {
                        //查询最后 认证失败的认证信息
                        UserDPI userDPI = userDPIService.searchLatestUserDPIError(terminalTypeId, roleId, user.getId());
                        result.put("dPIErrorMsg", null == userDPI ? "亲，您上传的身份证图片有点模糊，请重新上传！" : userDPI.getDescription());
                    }

                    result.put("cardholder", user.getCardholder());//持卡人姓名
                    result.put("bankStatus", (null == user.getBankStatus() || 4 == user.getBankStatus().intValue()) ? 3 : user.getBankStatus());//绑定银行卡状态

                    //手续费基率
                    double feeRate = (null == user.getFeeRate()) ? 0.005 : user.getFeeRate();
                    result.put("feeRate", feeRate);
                    result.put("branchesBank", null != user.getBranchesBank() ? user.getBranchesBank() : "");
                    result.put("bBankProvince", null != user.getBBankProvince() ? user.getBBankProvince() : "");
                    result.put("bBankCity", null != user.getBBankCity() ? user.getBBankCity() : "");

                    //登录系统公共信息
                    List<LoginMessage> loginSystemMsg = loginMessageService.searchLoginSystemMsg(terminalTypeId, roleId);
                    Map<String, Object> element = null;
                    List<Map<String, Object>> loginSystemList = new ArrayList<Map<String, Object>>();
                    for (LoginMessage msg : loginSystemMsg) {
                        element = new LinkedHashMap<String, Object>();
                        element.put("msg", msg.getMessage());
                        loginSystemList.add(element);
                    }
                    //登录个人信息
                    List<LoginMessage> loginPersonalMsg = loginMessageService.searchLoginPersonalMsg(terminalTypeId, roleId, user.getId());
                    List<Map<String, Object>> loginPersonalList = new ArrayList<Map<String, Object>>();
                    for (LoginMessage msg : loginPersonalMsg) {
                        element = new LinkedHashMap<String, Object>();
                        element.put("msg", msg.getMessage());
                        loginPersonalList.add(element);
                    }
                    result.put("loginSystemMsg", loginSystemList);
                    result.put("loginPersonalMsg", loginPersonalList);
                    result.put("machineType", user.getMachineType());//终端机器类型
                    result.put("uuId", StringUtils.isEmpty(user.getUuId()) ? "" : user.getUuId());//终端机器唯一标识
                    result.put("channelId", user.getChannelId());//终端通道
                    result.put("isPayPwdNull", StringUtils.isEmpty(user.getPayPassword()) ? "1" : "0");//1 支付密码为空 0 存在支付密码
                    result.put("crashT1Type", user.getCrashT1Type());//1 支付密码为空 0 存在支付密码


                    log.debug(" 用户 " + user.getMobile() + " 登录成功！");
                    result.put("reqCode", "0000");
                    result.put("reqMsg", "用户登录成功！");
                    result.put("sessionId", getSession().getId());
                    int isBeta = 0;
                    if (user.getIsBeta() != 0)
                        isBeta = user.getIsBeta();
                    result.put("isBeta", isBeta);
                    sendAppMsg(result);

                    //将用户登录信息保存到 session 中
                    userService.saveMemcachedByUser(user);
                    getSession().setAttribute(SESSION_USER, user);

                } else {
                    if (1 == loginType.intValue()) {//手机号+密码 登录
                        log.warn("登录时，密码错误！");
                        sendAppErrorMsg("6006");
                    } else {//手机号+银行卡号 登录
                        log.warn("登录时，卡号没有被用户绑定！！");
                        sendAppErrorMsg("6007");
                    }
                }
            } else {
                log.warn("登录时，用户名不存在！");
                sendAppErrorMsg("6008");
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            log.debug("--- login() end ---");
        }
    }

    /**
     * 查询用户名（刷卡登录  步骤1）
     *
     * @return
     * @throws Exception
     */
    public String searchMobileByBankCard() throws Exception {
        log.debug("--- searchMobileByBankCard() start ---");
        JSONObject js = JSONObject.fromObject(getRequest().getAttribute(FC_DATA));

        if (js.containsKey("bankCard"))
            bankCard = js.getString("bankCard");

        log.debug("bankCard = " + bankCard);
        if (StringUtils.isBlank(bankCard)) {
            log.warn("查询用户名（刷卡登录  步骤1）时, 传入参数bankCard为空");
            sendAppErrorMsg("6001", "bankCard");
            return null;
        }
        try {
            Map<String, Object> result = new LinkedHashMap<String, Object>();
            List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
            Map<String, Object> element = null;
            user = new User();
            user.setDeleted(0);
            user.setBankCard(bankCard);
            List<User> userList = userService.searchEntityList(user);
            for (User u : userList) {
                element = new LinkedHashMap<String, Object>();
                element.put("mobile", u.getMobile());
                resultList.add(element);
            }

            if (resultList.size() > 0) {
                log.debug("查询用户名（刷卡登录  步骤1）成功！");
                result.put("reqCode", "0000");
                result.put("reqMsg", "查询用户手机列表成功！");
                result.put("userList", resultList);
                sendAppMsg(result);
            } else {
                log.warn("查询用户名（刷卡登录  步骤1）时, bankCard 没有被用户绑定过！");
                sendAppErrorMsg("6007");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            log.debug("--- searchMobileByBankCard() end ---");
        }
        return null;
    }

    /**
     * 用户注销
     *
     * @return
     */
    public String userLogout() throws Exception {
        log.debug("--- userLogout() start ---");
        JSONObject js = JSONObject.fromObject(getRequest().getAttribute(FC_DATA));

        if (js.containsKey("userId"))
            userId = Long.parseLong(js.getString("userId"));


        log.debug("userId = " + userId);
        if (null == userId) {
            log.warn("用户注销时, 传入参数userId为空");
            sendAppErrorMsg("6001", "userId");
            return null;
        }
        try {

            user = userService.getUserById(userId);
            if (null != user) {
                boolean status = userService.userLogout(userId);
                log.warn("用户注销成功!");
                Map<String, Object> result = new LinkedHashMap<String, Object>();
                result.put("reqCode", "0000");
                result.put("reqMsg", "用户注销成功！");
                log.debug("注册成功！");
                sendAppMsg(result);
            } else {
                log.warn("用户注销时, 传入userId=" + userId + " 不存在用户！");
                sendAppErrorMsg("6012", userId + "");
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            log.debug("--- userLogout() end ---");
        }
        return null;
    }

    /**
     * 修改密码
     *
     * @return
     */
    public String updateUserPasseword() throws Exception {
        log.debug("--- updateUserPasseword() start ---");
        JSONObject js = JSONObject.fromObject(getRequest().getAttribute(FC_DATA));

        if (js.containsKey("userId"))
            userId = Long.parseLong(js.getString("userId"));
        if (js.containsKey("oldPassword"))
            oldPassword = js.getString("oldPassword");
        if (js.containsKey("password"))
            password = js.getString("password");

        log.debug("userId = " + userId);
        log.debug("oldPassword  = " + oldPassword);
        log.debug("password   = " + password);

        if (null == userId) {
            log.warn("修改密码时, 传入参数userId为空");
            sendAppErrorMsg("6001", "userId");
            return null;
        }
        if (StringUtils.isBlank(oldPassword)) {
            log.warn("修改密码时, 传入参数oldPasseword为空");
            sendAppErrorMsg("6001", "oldPassword");
            return null;
        }
        if (StringUtils.isBlank(password)) {
            log.warn("修改密码时, 传入参数password为空");
            sendAppErrorMsg("6001", "password");
            return null;
        }
        try {
            oldPassword = oldPassword.trim();
            password = password.trim();
            user = userService.getUserById(userId);
            log.debug("oldPassword  = " + oldPassword);
            log.debug("password   = " + password);
            log.debug("数据库密码：" + user.getPassword());
            log.debug("数据库密码：" + MD5.mD5ofStr(oldPassword));
            if (null != user) {
                if (user.getPassword().equals(MD5.mD5ofStr(oldPassword))) {//与原密码相同
                    user.setPassword(MD5.mD5ofStr(password));
                    boolean status = userService.updateUserPasseword(user);
                    if (status) {
                        log.debug("修改密码成功!");
                        Map<String, Object> result = new LinkedHashMap<String, Object>();
                        result.put("reqCode", "0000");
                        result.put("reqMsg", "修改密码成功！");
                        sendAppMsg(result);
                    } else {
                        log.warn("修改密码失败，memcache错误！");
                        sendAppErrorMsg("6011");//未知错误
                    }
                } else {
                    log.warn("修改密码时, 原密码输入错误！");
                    sendAppErrorMsg("6010");//未知错误
                }
            } else {
                log.warn("不存在用户userId=" + userId + " 的用户！");
                sendAppErrorMsg("6012", userId + "");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            log.debug("--- updateUserPasseword() end ---");
        }
        return null;
    }

    /**
     * 绑定刷卡器
     *
     * @return
     * @throws Exception
     */
    public String bindingMachine() throws Exception {
        log.debug("--- bindingMachine() start ---");
        if (null != getJsonString("userId"))
            userId = Long.parseLong(getJsonString("userId"));
        if (null != getJsonString("machineType"))
            machineType = Integer.parseInt(getJsonString("machineType"));
        if (null != getJsonString("uuId"))
            uuId = getJsonString("uuId");
        if (null == userId) {
            log.warn("绑定刷卡器时, 传入参数userId为空");
            sendAppErrorMsg("6001", "userId");
            return null;
        }
        if (null == machineType) {
            log.warn("绑定刷卡器时, 传入参数machineType为空");
            sendAppErrorMsg("6001", "machineType");
            return null;
        }
        try {
            user = userService.getUserById(userId);
            user.setMachineType(machineType);
            user.setUuId(uuId);

            int flag = userService.bindingMachine(user);
            Map<String, Object> result = new LinkedHashMap<String, Object>();
            if (flag > 0) {
                log.warn("绑定刷卡器成功！");
                result.put("reqCode", "0000");
                result.put("reqMsg", "绑定刷卡器成功！！");
                sendAppMsg(result);
            } else {
                log.warn("绑定刷卡器失败！");
                sendAppErrorMsg("9999");
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            log.debug("--- bindingMachine() end ---");
        }
    }

    /**
     * 设备签到
     * _M 密钥密文 _C 密钥校验值 _F 最终密钥
     *
     * @return
     */
    public String deviceLogin() throws Exception {
        log.debug("--- deviceLogin() start ---");
        JSONObject js = JSONObject.fromObject(getRequest().getAttribute(FC_DATA));

        if (js.containsKey("deviceId")) {
            deviceId = js.getString("deviceId");
        }
        if (js.containsKey("userId")) {
            userId = Long.parseLong(js.getString("userId"));
        }
        if (StringUtils.isBlank(deviceId)) {
            log.warn("设备签到时, 传入参数deviceId为空");
            sendAppErrorMsg("6001", "deviceId");
            return null;
        }
        if (userId == null) {
            log.warn("设备签到时, 传入参数userId为空");
            sendAppErrorMsg("6001", "userId");
            return null;
        }
        try {
            String check_Data = "00000000000000000000000000000000";
            DeviceKey deviceKey = new DeviceKey();
            deviceKey.setDeviceId(deviceId);
            deviceKey = deviceKeyService.searchEntity(deviceKey);
            Map<String, Object> result = new LinkedHashMap<String, Object>();
            if (deviceKey != null) {
                String masterKey = deviceKey.getMasterKey();

                String pinKey = Des3.generate32Key();
                String pinKey_M = Des3.encode3DES(pinKey, masterKey);
                String pinKey_C = Des3.encode3DES(check_Data, pinKey).substring(0, 8);
                String pinKey_F = pinKey_M + pinKey_C;

                String trackKey = Des3.generate32Key();
                String trackKey_M = Des3.encode3DES(trackKey, masterKey);
                String trackKey_C = Des3.encode3DES(check_Data, trackKey).substring(0, 8);
                String trackKey_F = trackKey_M + trackKey_C;

                String macKey = Des3.generate32Key();
                String macKey_M = Des3.encode3DES(macKey, masterKey);
                String macKey_C = Des3.encode3DES(check_Data, macKey).substring(0, 8);
                String macKey_F = macKey_M + macKey_C;

                String sensitiveKey = Des3.generate32Key();
                String sensitiveKey_M = Des3.encode3DES(sensitiveKey, masterKey);
                String sensitiveKey_C = Des3.encode3DES(check_Data, sensitiveKey).substring(0, 8);
                String sensitiveKey_F = sensitiveKey_M + sensitiveKey_C;

                deviceKey.setPinKey(pinKey);
                deviceKey.setTrackKey(trackKey);
                deviceKey.setMacKey(macKey);
                deviceKey.setSensKey(sensitiveKey);
                deviceKey.setIs_login("1");
                deviceKey.setLast_userId(userId.intValue());
                deviceKeyService.updateEntity(deviceKey);

                result.put("reqCode", "0000");
                result.put("reqMsg", "设备签到成功!");
                result.put("deviceId", deviceId);
                result.put("pinKey", pinKey_F);
                result.put("trackKey", trackKey_F);
                result.put("macKey", macKey_F);
                result.put("sensitiveKey", sensitiveKey_F);
            } else {
                result.put("reqCode", "0001");
                result.put("reqMsg", "未知设备!");
            }
            sendAppMsg(result);
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            log.debug("--- deviceLogin() end ---");
        }
    }

    /**
     * 1.1.20、修改 结算类型
     *
     * @return
     * @throws Exception
     */
    public String updateCrashT1Type() throws Exception {
        log.debug("--- updateCrashT1Type() start ---");

        if (true) {
            Map<String, Object> result = new LinkedHashMap<String, Object>();
            result.put("reqCode", "0001");
            result.put("reqMsg", "功能暂停！");
            sendAppMsg(result);
            return null;
        }

        if (null != getJsonString("userId"))
            userId = Long.parseLong(getJsonString("userId"));
        if (null != getJsonString("crashT1Type"))
            crashT1Type = Integer.parseInt(getJsonString("crashT1Type"));
        if (null != getJsonString("verifiType"))
            verifiType = Integer.parseInt(getJsonString("verifiType"));
        if (null != getJsonString("codeOrPswd"))
            codeOrPswd = getJsonString("codeOrPswd");


        if (null == userId) {
            log.warn("修改结算类型时, 传入参数userId为空");
            sendAppErrorMsg("6001", "userId");
            return null;
        }
        if (null == crashT1Type) {
            log.warn("修改结算类型时, 传入参数crashT1Type为空");
            sendAppErrorMsg("6001", "crashT1Type");
            return null;
        }
        if (null != verifiType && verifiType != 0) {
            if (null == codeOrPswd) {
                log.warn("修改结算类型时, 传入参数codeOrPswd为空");
                sendAppErrorMsg("6001", "codeOrPswd");
                return null;
            }
        }

        try {
            user = userService.getUserById(userId);

            //验证 手机验证码
            boolean verifi = verifiService.verifiCode(VerifiService.CODETYPE_UPCRASHT1TYPE, verifiType, codeOrPswd, user.getMobile(), null);
            if (!verifi) {
                log.warn("修改结算类型时, 验证失败！");
                sendAppErrorMsg("6014");
                return null;
            }

            user.setCrashT1Type(crashT1Type);
            int flag = userService.updateCrashT1Type(user);
            Map<String, Object> result = new LinkedHashMap<String, Object>();
            if (flag > 0) {
                log.warn("修改结算类型成功！");
                result.put("reqCode", "0000");
                result.put("reqMsg", "修改结算类型成功！！");
                sendAppMsg(result);
            } else {
                log.warn("修改结算类型成功！");
                sendAppErrorMsg("9999");
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            log.debug("--- updateCrashT1Type() end ---");
        }
    }

    /**
     * 1.1.23 获取秒到绑定银行卡列表
     * @return
     * @throws Exception
     */
    public String getSSBankCardList() throws Exception {
        if (null != getJsonString("clientType"))
            clientType = Integer.parseInt(getJsonString("clientType")); // 客户端类型：1网站 2安卓 3iphone 4ipad
        if (null != getJsonString("terminalTypeId"))
            terminalTypeId = Long.parseLong(getJsonString("terminalTypeId")); // 终端类型
        if (null != getJsonString("roleId"))
            roleId = Long.parseLong(getJsonString("roleId")); // 角色id
        if (null != getJsonString("userId"))
            userId = Long.parseLong(getJsonString("userId")); // 用户id


        Map<String, Object> resultMap = new LinkedHashMap<String, Object>();
        try {
           /* SSBindCards bindCards = new SSBindCards();
            bindCards.setUserId(userId);
            bindCards.setOtherParam("status <> 0");
            bindCards.setStatus(1);
            List<SSBindCards> cards = bindCardsService.searchEntityList(bindCards);*/
            List<SSBindCards> cards =  bindCardsService.selectBindCardsListByUserId(userId);
            List<Map<String,Object>> cardList = new ArrayList<Map<String,Object>>();
            Map<String,Object> map = null;
            for (SSBindCards ssBindCards : cards){
                map = new LinkedHashMap<String,Object>();
                map.put("id", String.valueOf(ssBindCards.getId()));
                map.put("cardNumber", ssBindCards.getCardNumber());
                if(StringUtils.isNotBlank(ssBindCards.getIssueBank())){
                    map.put("issueBank", ssBindCards.getIssueBank());
                }else {
                    map.put("issueBank", "");
                }

                map.put("status", String.valueOf(ssBindCards.getStatus()));//状态
                cardList.add(map);
            }
            resultMap.put("reqCode","0000");
            resultMap.put("reqMsg","获取绑定卡成功");
            resultMap.put("cardList", cardList);
            sendAppMsg(resultMap);
        }catch (Exception e){
            resultMap.put("reqCode","9999");
            resultMap.put("reqMsg","程序异常!");
            sendAppMsg(resultMap);
            e.printStackTrace();
        }
        return null;
    }



    /**
     * 绑定秒到银行卡号
     * @return
     * @throws Exception
     */
    public String bindSSBankCard() throws Exception {
        log.debug("-----------  bindSSBankCard() start  ----------------");

       /* String fc_data = getRequest().getParameter("fc_data");
        if(fc_data!=null){
        	 getRequest().setAttribute("fc_data", fc_data);
        }*/

        acthCardDataVerification();
        String cardNumber = ""; //银行卡卡号
        String userName = "";   //持卡人姓名
        String issueBank = "";  // 开户行
        String idCard = "";     // 持卡人身份证号
        String cvv2 = "";        // cvv校验码
        String dueDate = "";    // 卡片有效期
        String cardHolder = "";  // 持卡人姓名
        String phoneNumber = "";// 银行预留手机号
        String verifyCode = "";// 短信验证码
        String jsonString = getJsonString("clientType");
        if (null != getJsonString("clientType"))
            clientType = Integer.parseInt(getJsonString("clientType")); // 客户端类型：1网站 2安卓 3iphone 4ipad
        if (null != getJsonString("terminalTypeId"))
            terminalTypeId = Long.parseLong(getJsonString("terminalTypeId")); // 终端类型
        if (null != getJsonString("roleId"))
            roleId = Long.parseLong(getJsonString("roleId")); // 角色id
        if (null != getJsonString("userId"))
            userId = Long.parseLong(getJsonString("userId")); // 用户id
        if (null != getJsonString("cardNumber")) {
            cardNumber = getJsonString("cardNumber"); // 银行卡卡号

        }
        if (null != getJsonString("userName")){
            userName = getJsonString("userName");     // 持卡人姓名
            cardHolder =  userName;
        }
        if (null != getJsonString("issueBank")){
            issueBank = getJsonString("issueBank"); // 开户行
        }
        if (null != getJsonString("idCard")){
            idCard = getJsonString("idCard");        // 身份证号
        }
        if (null != getJsonString("cvv2")){
            cvv2 = getJsonString("cvv2");              // cvv校验码
        }
        if (null != getJsonString("dueDate")){
            dueDate = getJsonString("dueDate");      // 卡片有效期
        }
        if (null != getJsonString("phoneNumber")){
            phoneNumber = getJsonString("phoneNumber"); // 银行预留手机号
        }
       /** if (null != getJsonString("cardHolder")){
            cardHolder = getJsonString("cardHolder"); // 持卡人姓名
        }*/
        if (null != getJsonString("verifyCode")){
        	verifyCode = getJsonString("verifyCode"); // 短信验证码
        }
        if (StringUtils.isEmpty(cardNumber)) {
            log.warn("绑定秒到银行卡时, 传入参数cardNumber为空");
            sendAppErrorMsg("6001", "cardNumber");
            return null;
        }
        if (StringUtils.isEmpty(userName)) {
            log.warn("绑定秒到银行卡时, 传入参数userName为空");
            sendAppErrorMsg("6001", "userName");
            return null;
        }
        if (StringUtils.isEmpty(issueBank)) {
            log.warn("绑定秒到银行卡时, 传入参数issueBank为空");
            sendAppErrorMsg("6001", "issueBank");
            return null;
        }
        if (StringUtils.isEmpty(idCard)) {
            log.warn("绑定秒到银行卡时, 传入参数idCard为空");
            sendAppErrorMsg("6001", "idCard");
            return null;
        }
        if (StringUtils.isEmpty(cvv2)) {
            log.warn("绑定秒到银行卡时, 传入参数cvv2为空");
            sendAppErrorMsg("6001", "cvv2");
            return null;
        }
        if (StringUtils.isEmpty(dueDate)) {
            log.warn("绑定秒到银行卡时, 传入参数dueDate为空");
            sendAppErrorMsg("6001", "dueDate");
            return null;
        }
        if (StringUtils.isEmpty(phoneNumber)) {
            log.warn("绑定秒到银行卡时, 传入参数phoneNumber为空");
            sendAppErrorMsg("6001", "phoneNumber");
            return null;
        }
        if (StringUtils.isEmpty(cardHolder)){
            log.warn("绑定秒到银行卡时, 传入参数cardHolder为空");
            sendAppErrorMsg("6001", "cardHolder");
            return null;
        }
        log.debug("clientType = " + clientType);
        log.debug("terminalTypeId = " + terminalTypeId);
        log.debug("roleId = " + roleId);
        log.debug("userId = " + userId);
        log.debug("cardNumber = " + cardNumber);
        log.debug("userName = " + userName);
        log.debug("issueBank = " + issueBank);
        log.debug("cvv = " + cvv2);
        log.debug("dueDate = " + dueDate);
        log.debug("phoneNumber = " + phoneNumber);
        try{

        	//检验短信验证码

            UserNocardpayLog userNocardpayLog = new UserNocardpayLog();
            //userNocardpayLog.setOrderid(orderid);
            String transamount = settingsService.getMainValueByFk("BIND_CARD_PAY_MONEY");
            userNocardpayLog.setUserid(userId);
            userNocardpayLog.setCardnumber(cardNumber);
            userNocardpayLog.setDuedate(dueDate);
            userNocardpayLog.setCardholder(userName);
            userNocardpayLog.setIdcard(idCard);
            userNocardpayLog.setPhonenumber(phoneNumber);
            userNocardpayLog.setCvv2(cvv2);

            userNocardpayLog.setTransamount(new BigDecimal(transamount));//交易金额
            userNocardpayLog.setTranstime(new Date());
            userNocardpayLog.setProductcode("16");//商品编号
            userNocardpayLog.setProductname("实名认证");
            userNocardpayLog.setProductdesc("实名认证");
            userNocardpayLog.setUsercode("");//用户标识
            userNocardpayLog.setUserip("127.0.0.1");//
           // userNocardpayLog.setUyderid(uyderid);
            userNocardpayLog.setBankcardtype(2);//银行卡类型 1：储蓄卡 2：信用卡

            Map resultMap =  bindCardsService.bindBankCard(userNocardpayLog, verifyCode);

            String reqCode =String.valueOf(resultMap.get("reqCode"));
            if(reqCode.equals("0000")){
            	String loginName= "";
				User user = userService.getUserById(userId);
				if(user!=null)
				 loginName = user.getLoginName();// 登录名
				SSBindCards bindCards = new SSBindCards();
				bindCards.setUserId(userId);
				bindCards.setLoginName(loginName);
				bindCards.setCardNumber(cardNumber);
				bindCards.setIdCard(idCard);
				bindCards.setIssueBank(issueBank);
				bindCards.setDueDate(dueDate);
				bindCards.setCardHolder(cardHolder);
				bindCards.setPhoneNumber(phoneNumber);
				bindCards.setCvv2(cvv2);
				bindCards.setStatus(1);
				Long flag = bindCardsService.insertEntity(bindCards);
            }
            sendAppMsg(resultMap);

        }catch (Exception e){
            e.printStackTrace();
            sendAppErrorMsg("9999");
        }

        return null;
    }


    /**
     * 1.1.6、找回密码
     *
     * @return
     * @throws Exception
     */
    public String retrievePassword() throws Exception {
        log.debug("--- retrievePassword() start ---");
        if (null != getJsonString("mobile"))
            mobile = getJsonString("mobile");
        if (null != getJsonString("userName"))
            userName = getJsonString("userName");
        if (null != getJsonString("identityCard"))
            identityCard = getJsonString("identityCard");
        if (null != getJsonString("password"))
            password = getJsonString("password");
        if (null != getJsonString("verifiType"))
            verifiType = Integer.parseInt(getJsonString("verifiType"));
        if (null != getJsonString("codeOrPswd"))
            codeOrPswd = getJsonString("codeOrPswd");
        terminalTypeId = Long.parseLong(getJsonString("terminalTypeId"));
        roleId = Long.parseLong(getJsonString("roleId"));

        if (StringUtils.isEmpty(mobile)) {
            log.warn("找回密码时, 传入参数mobile为空");
            sendAppErrorMsg("6001", "mobile");
            return null;
        }
        if (StringUtils.isEmpty(userName)) {
            log.warn("找回密码时, 传入参数userName为空");
            sendAppErrorMsg("6001", "userName");
            return null;
        }
        if (StringUtils.isEmpty(identityCard)) {
            log.warn("找回密码时, 传入参数identityCard为空");
            sendAppErrorMsg("6001", "identityCard");
            return null;
        }
        if (StringUtils.isEmpty(password)) {
            log.warn("找回密码时, 传入参数password为空");
            sendAppErrorMsg("6001", "password");
            return null;
        }
        if (null != verifiType && verifiType != 0) {
            if (null == codeOrPswd) {
                log.warn("找回密码时, 传入参数codeOrPswd为空");
                sendAppErrorMsg("6001", "codeOrPswd");
                return null;
            }
        }

        log.debug("mobile   = " + mobile);
        log.debug("userName   = " + userName);
        log.debug("identityCard   = " + identityCard);
        log.debug("password   = " + password);
        log.debug("verifiType   = " + verifiType);
        log.debug("codeOrPswd   = " + codeOrPswd);


        try {
            user = new User();
            user.setLoginName(mobile);
            user.setTerminalTypeId(terminalTypeId);
            user.setRoleId(roleId);

            user = userService.searchEntity(user);

            if (user == null) {
                log.debug("找回密码时验证失败！不存在用户名为" + mobile + "的用户！");
                sendAppErrorMsg("6105");
                return null;
            }

            if (!identityCard.equals(user.getIdentityCard())) {

                log.debug("找回密码时验证失败！身份证号验证不通过！");
                sendAppErrorMsg("6105");
                return null;
            }

            if (!userName.equals(user.getCardholder())) {

                log.debug("找回密码时验证失败！用户名验证不通过！");
                sendAppErrorMsg("6105");
                return null;
            }

            user.setPassword(MD5.mD5ofStr(password));
            int flag = userService.updateEntity(user);

            Map<String, Object> result = new LinkedHashMap<String, Object>();
            if (flag > 0) {
                log.warn("找回密码成功！");
                result.put("reqCode", "0000");
                result.put("reqMsg", "成功找回密码！！");
                sendAppMsg(result);
            } else {
                log.warn("找回密码失败！");
                sendAppErrorMsg("9999");
            }

            return null;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            log.debug("--- retrievePassword() end ---");
        }

    }
    /**
     * 鉴权接口
     * @return string
     * @author lishijie
     * 1.接收参加
     * 2.查询库是否存在  存在直接返回
     * 3.调用接口
     * 4.入库
     * 5.返回客户端
     */
    public String authCard(){
    	Map<String, Object> resultMap = new HashMap<String, Object>();
    	try {
    		if(!acthCardDataVerification())return null;
    		String userId = getJsonString("userId");
    		String cardNumber = getJsonString("cardNumber");
    		String userName = getJsonString("userName");
    		String idCard = getJsonString("idCard");
    		String cvv2 = getJsonString("cvv2");
    		String dueDate = getJsonString("dueDate");
    		String phoneNumber = getJsonString("phoneNumber");
    		String issueBank = getJsonString("issueBank");
    		String roleId = getJsonString("roleId");
    		String terminalTypeId = getJsonString("terminalTypeId");

    		UserVerifycardsLog userVerifycardsLog = new UserVerifycardsLog();
    		userVerifycardsLog.setUserid(Long.valueOf(userId));
    		userVerifycardsLog.setCardnumber(cardNumber);
    		userVerifycardsLog.setIdcard(idCard);
    		userVerifycardsLog.setPhonenumber(phoneNumber);
    		userVerifycardsLog.setCvv2(cvv2);
    		userVerifycardsLog.setDuedate(dueDate);
    		userVerifycardsLog.setCardholder(userName);
    		userVerifycardsLog.setIssubank(issueBank);
    		resultMap = bindCardsService.NZTAuthCard(userVerifycardsLog,Long.parseLong(roleId),Long.parseLong(terminalTypeId));
    		sendAppMsg(resultMap);
		} catch (Exception e) {
			resultMap.put("reqCode","9999");
			resultMap.put("reqMsg","程序异常!");
			sendAppMsg(resultMap);
			e.printStackTrace();
		}
		return null;
    }
    /**
     * 解绑银行卡
     * @return
     */
    public String deleteSSBankCard() {
    	Map<String, Object> resultMap = new HashMap<String, Object>();
    	try {
    		String userId = getJsonString("userId");
    		String cardNumber = getJsonString("cardNumber");
            String id = getJsonString("id");
            String status = getJsonString("status");
            String verifyCode = getJsonString("verifyCode");
			if (null == userId) {
				log.warn("解绑银行卡号时, 传入参数userId为空");
				sendAppErrorMsg("6001", "userId");
				return null;
			}
			if (StringUtils.isEmpty(cardNumber)) {
				log.warn("解绑秒到银行卡时, 传入参数cardNumber为空");
				sendAppErrorMsg("6001", "cardNumber");
				return null;
			}
            if (StringUtils.isEmpty(status)){
                log.warn("解绑秒到银行卡时,传入参数status为空");
                sendAppErrorMsg("6001","status");
                return null;

            }
            if (!"4".equals(status)){//状态为4(认证失败)时,不校验验证码
                if (StringUtils.isEmpty(verifyCode)){
                    log.warn("解绑银行卡时,传入参数verifyCode为空");
                    sendAppErrorMsg("6001","verifyCode");
                    return null;
                }
                user = userService.getUserById(Long.valueOf(userId));
                boolean b = verifiService.verifiCode(VerifiService.CODETYPE_DELETECARDBIND, 1, verifyCode, user.getMobile(), null);
                if(!b){
                    resultMap.put("reqCode", "9999");
                    resultMap.put("reqMsg", "验证码错误!");
                    sendAppMsg(resultMap);
                    return null;
                }
            }
        	SSBindCards ssBindCards = new SSBindCards();
        	ssBindCards.setStatus(0);
        	SSBindCardsExample example = new SSBindCardsExample();
        	example.createCriteria().andUserIdEqualTo(Long.valueOf(userId)).andCardNumberEqualTo(cardNumber);
        	int i = bindCardsService.updateByExampleSelective(ssBindCards, example);
        	log.debug("成功更新：" + i +"条");
            //同时修改info_cardcer表中的认证状态修改为4
            CardCer cardCer = new CardCer();
            //cardCer.setStatus(1);
            cardCer.setBankCard(cardNumber);
            cardCer.setUserId(Long.valueOf(userId));
            cardCer.setVerifiType(2);
            List<CardCer> cardCerList = cardCerService.searchEntityList(cardCer);
            if (null != cardCerList){
                for (CardCer cer : cardCerList){
                    cer.setStatus(5);
                    int j = cardCerService.updateEntity(cer);
                }
            }
        	resultMap.put("reqCode","0000");
			resultMap.put("reqMsg","解绑成功!");
			sendAppMsg(resultMap);
		} catch (Exception e) {
			resultMap.put("reqCode","9999");
			resultMap.put("reqMsg","解绑失败!");
			sendAppMsg(resultMap);
			e.printStackTrace();
		}

    	return null;
    }
    /**
     * 获取秒到认证方式
     * @return lishijie
     */
    public String getSSBindCardsPattern(){
    	Map<String, String> resultMap = new HashMap<String,String>();
    	try {
    		Settings jsonStr = settingsService.getSettingsByFk("BIND_CARDS_PATTERN");
    		resultMap = JSONUtil.parseToBean(jsonStr.getMainValue());
    		resultMap.put("reqCode","0000");
			resultMap.put("reqMsg","获取参数正常!");

		} catch (Exception e) {
			e.printStackTrace();
			log.error("绑定银行卡认证类型:"+e.getMessage());
			resultMap.put("reqCode","9999");
			resultMap.put("reqMsg","接口异常!");
		}
    	sendAppMsg(resultMap);
    	return null;
    }

    /**
     * 鉴权数据校验
     * @return
     * @throws Exception
     */
    public boolean acthCardDataVerification() throws Exception{
    	Map<String, Object> resultMap = new HashMap<String, Object>();
    	String issueBank = getJsonString("issueBank");
    	String idCard = getJsonString("idCard");
    	String userId = getJsonString("userId");
		String cardNumber = getJsonString("cardNumber");
		/*String bankName = bankCodeService.searchBankNameByCard(cardNumber);
    	if(!bankName.contains(cardNumber)){//校验开户行
    		resultMap.put("reqCode","9999");
			resultMap.put("reqMsg","开户行错误!");
			sendAppMsg(resultMap);
			 return false;
    	}*/
    	//校证是否已经绑定过
    	SSBindCards ssBindCards = new SSBindCards();
    	ssBindCards.setUserId(Long.valueOf(userId));
    	ssBindCards.setCardNumber(cardNumber);
    	ssBindCards.setStatus(1);
    	SSBindCards bindCrad = bindCardsService.searchEntity(ssBindCards);
    	if(bindCrad!=null){
    		resultMap.put("reqCode","9999");
			resultMap.put("reqMsg","不能重复绑定!");
			sendAppMsg(resultMap);
			return false;
    	}
    	// 0416 验证卡有效期 有效期 大于 当前 时间有效
    	String dueDate = getJsonString("dueDate");
      	Date cardDate = DateUtils.parseDateByFormat(dueDate,"MMyy");
      	Date toDay = DateUtils.getDay(new Date());
      	long day = DateUtils.subDateGetDay(toDay,cardDate);
      	if(day <= 0){
      		resultMap.put("reqCode","9999");
			resultMap.put("reqMsg","卡片已过期!");
			sendAppMsg(resultMap);
			return false;
      	}
    	return true;
    }

    /**
     * 修改银行卡格式为123456****1122
     * @return
     */
    public String modifyBankCard(String bankCard){
        if(StringUtils.isBlank(bankCard)){
            return "";
        }else {
            String head = bankCard.substring(0,6);
            String foot = bankCard.substring(bankCard.length()-4,bankCard.length());
            int bodyLength = bankCard.length() - head.length() - foot.length();
            StringBuilder sb = new StringBuilder("");
            for(int i=0;i<bodyLength;i++){
                sb.append("*");
            }
            return head + sb.toString() + foot;
        }
    }

    /**
     * 微信注册获取用户信息
     * @author lishijie
     *  activeCode＝AY7FDUG27MDL5YMQGK
     *  activationCode
     * @throws Exception
     */
    public String customerRegisterFetchInfo() throws Exception{
    	//判断激活码是否被注册
    	 String activationCode = getRequest().getParameter("activationCode");
    	 if (StringUtils.isBlank(activationCode)) {
             log.warn("用户注册时, 传入参数activationCode为空");
             sendWeChatErrorMsg("6001", "activationCode");
             return null;
         }

         //112 2  判断激活码 是否存在 不存在返回 错误信息
         ActivationCode activationCodeBean = activationCodeService.searchACodeToRegister(activationCode, terminalTypeId, 2l);
         if(activationCodeBean == null){
        	 sendWeChatErrorMsg("6009");
         }
         Long terminalTypeId = activationCodeBean.getTerminalTypeId();

         User user = new User();
         user.setActivationCode(activationCodeBean.getCode());
         user.setTerminalTypeId(terminalTypeId);
         user = userService.searchEntity(user);

        //判断支付还是微信请求
        String header = getRequest().getHeader("user-agent").toLowerCase();
        log.info("客户端请求信息========>{}",header);


         StringBuffer sb = new StringBuffer();
         //判断已激活 并且实名认证判断 为 审批中 与审批通过 通道为74
         if (1 == activationCodeBean.getIsActivation().intValue() && user != null &&(1 == user.getDPIStatus() || 2 == user.getDPIStatus()) && (user.getChannelId() == OfficialAccPayBaseAction.TC_JQ || user.getChannelId() == OfficialAccPayBaseAction.TC_JQ_SECOND || user.getChannelId() == OfficialAccPayBaseAction.TC_HSM) ) {

             if(header.contains("micromessenger")){
                 String JQCusId = "";
                 if(user!=null && OfficialAccPayBaseAction.TC_JQ_SECOND == user.getChannelId().intValue()){//进钱秒到
                     Settings settings = settingsService.getSettingsByFk("JQ_SECOND_STATUS");
                     Integer weChartStatus = Integer.valueOf(settings.getMainValue());
                     if(1 == weChartStatus){
                         JQCusId = user.getJQCusId();
                     }
                 }

                 String getOpenIdUrl = settingsService.getMainValueByFk("GET_OPENID_URL");

                 log.info("微信客户请求...");
                 sb.append("<script>");
                 sb.append("window.location.href=\'"+getOpenIdUrl+"?");
                 if(StringUtils.isNotBlank(JQCusId)){
                     sb.append("c=" + JQCusId +"&");
                 }
                 sb.append("merUrl=http%3a%2f%2f");
                 sb.append(urlStr);
                 sb.append("%2fproOneMobile%2fuser%2fuserAction_customerRegister.action%3factivationCode%3d");
                 sb.append(activationCode);
                 sb.append("\'</script>");

             }else if(header.contains("aliapp")){

                 log.info("支付宝客户端请求...");
                 sb.append("<script>");
                 sb.append("window.location.href=\'http://");
                 sb.append(urlStr);
                 sb.append("/proOneMobile/user/userAction_customerRegister.action?activationCode=");
                 sb.append(activationCode);
                 sb.append("\'</script>");
             }else {
                 sendWeChatMsg("暂不支持此平台,请在微信或支付宝内完成交易!");
                 return null;
             }

         }else{
        	 String scope = "";
        	 String state = "";
             String oldurl = urlStr;
             TerminalType terminalType = terminalTypeService.searchTerminalTypeById(terminalTypeId);
             urlStr = terminalType.getRealmName();
        	  if(1 == activationCodeBean.getIsActivation().intValue() && user != null &&(1 == user.getDPIStatus() || 2 == user.getDPIStatus())){
        		  scope = "snsapi_base";//
        		  state = "trade";
                  String replace = getCodeUrl.replace("shop.zyxin.cn","app1.zhijianzhuan.com.cn/proOneMobile");
                  getCodeUrl = replace;
                  log.info( "微信支付,获取openId Url:{}",getCodeUrl);
        	  }else{//注册用各自公众号登录
                  //TerminalType terminalType = terminalTypeService.searchTerminalTypeById(terminalTypeId);
                  appid = terminalType.getPublicKey();
        		  scope = "snsapi_userinfo";//
        		  state = "register";
                  getCodeUrl=  getCodeUrl.replace(oldurl,urlStr);
                  log.info( "微信注册,获取openId Url========>:{}",getCodeUrl);
        	  }

             sb.append("<script>");
             sb.append("window.location.href=\'http://");
             //获取 openId code 的值
             sb.append(getCodeUrl);
             sb.append("?appid="+appid);
             sb.append("&scope="+scope+"&state="+state);
             sb.append("&redirect_uri=http%3a%2f%2f");
             sb.append(urlStr);
             sb.append("%2fproOneMobile%2fuser%2fuserAction_getOpenIdAndRedirect.action%3factivationCode%3d");
             sb.append(activationCode);
             sb.append("\'");
             sb.append("</script>");
         }
         log.info("请求重定向地址===>：{}",sb.toString());
         try {
 			OutputStream os = getResponse().getOutputStream();
 			os.write(sb.toString().getBytes("UTF-8"));
 			os.flush();
 			os.close();
 		} catch (Exception e) {
 			e.printStackTrace();
 			log.error("登录url重定向异常:{}",e);
 		}
    	//并获取用户信息
	    return null;
    }

    /**
     *  服务商获取openId 再重定向
     */
	public String getOpenIdAndRedirect() {
		try {
			String activationCode = getRequest().getParameter("activationCode");
			String code = getRequest().getParameter("code");// 微信参数
			String state = getRequest().getParameter("state");// 微信参数 注册/交易

			 log.info("获取opnId: activationCode={} code={} access_token={}  state={}",new Object[]{activationCode,code,state});
			if (StringUtils.isBlank(activationCode)) {
				log.warn("用户注册时, 传入参数activationCode为空");
				sendWeChatErrorMsg("6001", "activationCode");
				return null;
			}
			if (StringUtils.isBlank(code) ) {// 微信
				log.info("传入参数code为空");
				sendWeChatErrorMsg("6001", "code");
				return null;
			}
			if (StringUtils.isBlank(state) ) {// 微信
				log.info("传入参数state为空");
				sendWeChatErrorMsg("6001", "state");
				return null;
			}
			 ActivationCode activationCodeBean = activationCodeService.searchACodeToRegister(activationCode, terminalTypeId, 2l);
	         if (null == activationCodeBean) {
	        	 sendWeChatErrorMsg("6009");
	             return null;
	         }
	         Long terminalTypeId = activationCodeBean.getTerminalTypeId();

	         //注册
			//if (user == null || 0 == activationCodeBean.getIsActivation().intValue()|| (1 != user.getDPIStatus() && 2 != user.getDPIStatus())) {
	        if (state.equals("register")) {
				TerminalType terminalType = terminalTypeService.searchTerminalTypeById(terminalTypeId);
				appid = terminalType.getPublicKey();
				secret = terminalType.getPrivateKey();
				log.info("注册-获取公众号appid:{} secret:{} ", new Object[] { appid, secret });
			}

			Map<String, String> parameterMap = new HashMap<String, String>();
			parameterMap.put("appid", appid);
			parameterMap.put("secret", secret);
			parameterMap.put("code", code);
			parameterMap.put("grant_type", "authorization_code");
			String openIdInfo = HttpClientUtil.getSendData("https://api.weixin.qq.com/sns/oauth2/access_token", "UTF-8",parameterMap);
			log.info("获取交易openId----access_token----:" + openIdInfo);
			Map<String, String> resultMap = JSONUtil.parseToBean(openIdInfo);
			String openId = resultMap.get("openid");
			String access_token = resultMap.get("access_token");
			//获取url 把 openId activationCode channelType 从定向
			TerminalType terminalType = terminalTypeService.searchTerminalTypeById(terminalTypeId);
			String realmName = terminalType.getRealmName();

			StringBuffer sb = new StringBuffer();
			sb.append("<script>");
			sb.append("window.location.href=\'http://"+realmName+"/proOneMobile/user/userAction_customerRegister.action");
			sb.append("?openId="+openId);
			sb.append("&activationCode="+activationCode);
			sb.append("&access_token="+access_token);
			sb.append("\'");
			sb.append("</script>");

			OutputStream os = getResponse().getOutputStream();
			os.write(sb.toString().getBytes("UTF-8"));
			os.flush();
			os.close();
			log.info("域名重定向地址===>：{}",sb.toString());

		} catch (Exception e) {
			log.error("获取openId异常:{}",e);
		}

		return null;
	}


    /**
     * 注册页面 或 商户信息显示
     * @author lishijie

     */
    public String customerRegister() throws Exception{

    	 String activationCode = getRequest().getParameter("activationCode");
    	 String openId = getRequest().getParameter("openId");//
    	 String access_token = getRequest().getParameter("access_token");//微信参数
    	 log.info("activationCode={} openId={} access_token={}  state={}",new Object[]{activationCode,openId,access_token});
    	 if (StringUtils.isBlank(activationCode)) {
             log.warn("用户注册时, 传入参数activationCode为空");
             sendWeChatErrorMsg("6001", "activationCode");
             return null;
         }

    	 ActivationCode activationCodeBean = activationCodeService.searchACodeToRegister(activationCode, terminalTypeId, 2l);
         if (null == activationCodeBean) {
        	 sendWeChatErrorMsg("6009");
             return null;
         }
         Long terminalTypeId = activationCodeBean.getTerminalTypeId();

         getRequest().setAttribute("terminalTypeId", terminalTypeId);
         getRequest().setAttribute("activationCode", activationCode);
         getRequest().setAttribute("openId", openId);

   	     User user = new User();
         user.setActivationCode(activationCodeBean.getCode());
         user.setTerminalTypeId(terminalTypeId);
         user = userService.searchEntity(user);

        String noticeT1 = "非T0结算,该笔交易将在下个工作日到账";
        String noticeT0 = "10元以上秒到,秒到时间为:09:00-22:00";
        StringBuilder notice = new StringBuilder();

        if (user != null && (1 == user.getDPIStatus() || 2 == user.getDPIStatus()) && 1 == activationCodeBean.getIsActivation().intValue()) {
            getRequest().setAttribute("userId", user.getId());
 			getRequest().setAttribute("fullName", user.getNickName());

             if(user.getChannelId() == OfficialAccPayBaseAction.TC_JQ_SECOND){//进钱秒到
                 //判断支付还是微信请求
                 int appClient = 0;
                 String header = getRequest().getHeader("user-agent").toLowerCase();
                 if(header.contains("alipay") || header.contains("aliapp")){
                     appClient = 1; //AliPay
                 }else if(header.contains("micromessenger") || header.contains("mqqbrowser")){
                     appClient = 2; //WeChart
                 }
                 //获取进钱微信和支付宝秒到接口的状态
                 Settings settings = settingsService.getSettingsByFk("JQ_SECOND_STATUS");
                 Integer weChartStatus = Integer.valueOf(settings.getMainValue());
                 Integer aliPayStatus = Integer.valueOf(settings.getValue2());

                 if(StringUtils.isNotBlank(user.getJQCusId()) && StringUtils.isNotBlank(user.getJQMD5Key()) && user.getClearStatus() != 2 && user.getBankStatus() == 1){

                     if(1 == appClient){//AliPay
                         if(1 == aliPayStatus){
                             notice.append(noticeT0);
                         }else {
                             notice.append(noticeT1);
                         }
                     }else if (2 == appClient){//WeChart
                         if(1 == weChartStatus){
                             notice.append(noticeT0);
                         }else {
                             notice.append(noticeT1);
                         }
                     }
                 }else{
                     notice.append(noticeT1);
                 }
             }else{
                 notice.append(noticeT1);
             }
             getRequest().setAttribute("notice", notice.toString());
 			return "customerTrans";// 跳转到商户收款页面
 		}

		Map<String, String> parameterUserMap = new HashMap<String,String>();
		parameterUserMap.put("access_token", access_token);
		parameterUserMap.put("openid", openId);
		parameterUserMap.put("lang", "zh_CN");
		String userInfo = HttpClientUtil.getSendData("https://api.weixin.qq.com/sns/userinfo", "UTF-8", parameterUserMap);

		log.info("获取用户信息userInfo:"+userInfo);
		Map<String, Object> resultUserMap = JSONUtil.parseToBean(userInfo,Map.class);
		//userinfo
		getRequest().setAttribute("code", resultUserMap.get("code"));
		getRequest().setAttribute("nickname", resultUserMap.get("nickname"));
		getRequest().setAttribute("sex", resultUserMap.get("sex"));
		getRequest().setAttribute("country", resultUserMap.get("country"));
		getRequest().setAttribute("province", resultUserMap.get("province"));
		getRequest().setAttribute("city", resultUserMap.get("city"));
		getRequest().setAttribute("headimgurl", resultUserMap.get("headimgurl"));

 		//初始化查询
 		List<Bank> bankList = bankService.searchCleanBankList();//查询合作银行
 		getRequest().setAttribute("bankList", bankList);

        return "customerRegister";
    }


    //注册及重置密码
    public String customerRegisterResetPswd() throws Exception{
    	log.debug("--- register() start ---");
    	 String mobile = getRequest().getParameter("mobile");
    	 String password = getRequest().getParameter("password");
    	 String activationCode = getRequest().getParameter("activationCode");
    	 String terminalTypeId = getRequest().getParameter("terminalTypeId");
    	 String openId = getRequest().getParameter("openId");
    	 if (StringUtils.isBlank(password)) {
             log.warn("用户注册时, 传入参数mobile为空");
             sendWeChatErrorMsg("6001", "mobile");
             return null;
         }
    	 if (StringUtils.isBlank(password)) {
    		 log.warn("用户注册时, 传入参数password为空");
    		 sendWeChatErrorMsg("6001", "password");
    		 return null;
    	 }

    	 if (StringUtils.isBlank(activationCode)) {
    		 log.warn("用户注册时, 传入参数activationCode为空");
    		 sendWeChatErrorMsg("6001", "activationCode");
    		 return null;
    	 }

    	 if (StringUtils.isBlank(terminalTypeId)) {
    		 log.warn("用户注册时, 传入参数terminalTypeId为空");
    		 sendWeChatErrorMsg("6001", "terminalTypeId");
    		 return null;
    	 }

        clientType = 1;
        roleId = 2l;
        //String businessRangeId = getRequest().getParameter("businessRangeId");
        businessRangeId = 18l;//经营范围 其他
        String businessAddress = "未知";
        log.debug("action = " + action);
        log.debug("clientType = " + clientType);
        log.debug("terminalTypeId = " + terminalTypeId);
        log.debug("roleId = " + roleId);
        log.debug("activationCode = " + activationCode);
        log.debug("mobile = " + mobile);
        log.debug("password = " + password);
        log.debug("businessRangeId = " + businessRangeId);//经营范围ID 必填
        log.debug("businessAddress = " + businessAddress);//经营地址 必填

        if (StringUtils.isBlank(activationCode)) {
            log.warn("用户注册时, 传入参数activationCode为空");
            sendAppErrorMsg("6001", "activationCode");
            return null;
        }
        if (StringUtils.isBlank(mobile)) {
            log.warn("用户注册时, 传入参数mobile为空");
            sendAppErrorMsg("6001", "mobile");
            return null;
        }
        if (!RegularUtils.checkMobile(mobile)) {
            log.warn("用户注册时, 手机号格式错误");
            sendAppErrorMsg("6102");
            return null;
        }
        if (StringUtils.isBlank(password)) {
            log.warn("用户注册时, 传入参数password为空");
            sendAppErrorMsg("6001", "password");
            return null;
        }
        if (null == businessRangeId) {
            log.warn("用户注册时, 传入参数businessRangeId为空");
            sendAppErrorMsg("6001", "businessRangeId");
            return null;
        }
        if (StringUtils.isBlank(businessAddress)) {
            log.warn("用户注册时, 传入参数businessAddress为空");
            sendAppErrorMsg("6001", "businessAddress");
            return null;
        }

        try {

            mobile = mobile.trim();
            password = password.trim();

            user = new User();
            user.setMobile(mobile);
            user.setRoleId(roleId);
            user.setTerminalTypeId(Long.parseLong(terminalTypeId));
            user = userService.searchEntity(user);

            if (null != user) {
               user.setUuId(openId);
               user.setPassword(MD5.mD5ofStr(password));
               userService.updateEntity(user);
               JSONObject result = new JSONObject();
                log.debug("已注册！");//
                result.put("userId", user.getId());
            	result.put("code", "0");
            	result.put("msg", "注册成功!");
            	sendWeChatMsg(result.toString());
                return null;
            }

            //查询激活码对象
            ActivationHistory activationHistory = null;
            ActivationCode activationCodeBean = null;
            if (null != bankCard) {
                bankCard = bankCard.trim();
            }
            activationCodeBean = activationCodeService.searchACodeToRegister(activationCode, Long.parseLong(terminalTypeId), roleId);
            if (null == activationCodeBean) {
            	sendWeChatErrorMsg("6009");
                return null;
            } else {
                if (1 == activationCodeBean.getIsActivation().intValue()) {
                	sendWeChatErrorMsg("6013");
                    return null;
                }
            }
            //组装激活码用户注册历史记录对象
            activationHistory = new ActivationHistory();
            activationHistory.setCodeId(activationCodeBean.getId());
            activationHistory.setLat(lat);
            activationHistory.setLng(lng);
            activationHistory.setY(y);
            activationHistory.setX(x);

            user = new User();
            user.setTerminalTypeId(Long.parseLong(terminalTypeId));
            user.setRoleId(roleId);
            user.setClientType(clientType);
            user.setLoginName(mobile);//注意 用户名 改为
            user.setMobile(mobile);
            password = MD5.mD5ofStr(password);
            log.debug("md5 password = " + password);
            user.setPassword(password);
            user.setBankStatus(3);//默认  未认证
            user.setRoleType(1);
            user.setActive(1);
            user.setUuId(openId);
            //添加费率
            if (null != activationCodeBean) {
                user.setOrganizationId(activationCodeBean.getOrganizationId());//机构ID
                user.setFeeRate(activationCodeBean.getFeeRate());//手续费费率
                user.setClearRate(activationCodeBean.getClearRate());//结算费率
                user.setOwnBrokerageRate(activationCodeBean.getOwnBrokerageRate());//佣金比例
                user.setActivationCode(activationCode);//激活码
                user.setRoleId(activationCodeBean.getRoleId());
                user.setClearFee(activationCodeBean.getClearFee());
                user.setFdMaxFee(activationCodeBean.getFdMaxFee());
                user.setFdMinFee(activationCodeBean.getFdMinFee());
                user.setCashRate(null == activationCodeBean.getCashRate() ? 0.002 : activationCodeBean.getCashRate());//提现费率
                user.setFdFeeRate(activationCodeBean.getFdFeeRate());
            }
            //添加经营范围
            user.setBusinessRangeId(businessRangeId);
            user.setBusinessAddress(businessAddress);
            long channelId = Long.valueOf(settingsService.getMainValueByFk("MOBILE_REGISTER_DEFAULT_CHANNEL"));
            user.setChannelId(channelId);//默认 收款通道 DEFAULT_CHANNELID
            user.setMachineType(0);//默认 没有绑定终端
            user.setCrashT1Type(0);//系统T+1提现  模式  默认
            userId = userService.register(user, activationHistory);
            if (null != userId && userId > 0l) {
            	JSONObject result = new JSONObject();
                log.debug("注册成功！");//userId.toString()
                result.put("userId", userId);
            	result.put("code", "0");
            	result.put("msg", "注册成功!");
            	sendWeChatMsg(result.toString());

            } else {
                log.warn("注册失败！");
                sendWeChatErrorMsg("9999");//未知错误
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            log.debug("--- register() end ---");
        }


    }

    //绑定结算信息
    public String customerRegisterCreate() throws Exception{

    	log.debug("--- bindingBankCard() start ---");
        clientType = 1;
        roleId = 2l;

        //userId
        userId = Long.parseLong(getRequest().getParameter("userId"));//手机号
        mobile = getRequest().getParameter("phoneNo");//手机号
        userName = getRequest().getParameter("cusLgPson");//法人姓名
        identityCard = getRequest().getParameter("cusIDNo");//身份证号
        String sex = getRequest().getParameter("sex");//姓别
        bankCard = getRequest().getParameter("cusSettleAccNo");//银行号
        String cusName = getRequest().getParameter("cusName");//商户名称
        String openingBankId = getRequest().getParameter("cusSettleAccBank");//开户行 id
        openingBank = getRequest().getParameter("openingBank");//开户行 名称
        bBankProvince = Integer.parseInt(getRequest().getParameter("cusSettleProvince"));//省
        bBankCity = Integer.parseInt(getRequest().getParameter("cusSettleCity"));//市
        branchesBankId = Long.parseLong(getRequest().getParameter("cusSettleAccBankName"));//市
        String terminalTypeIdStr = getRequest().getParameter("terminalTypeId");//市

        log.debug("userId = " + userId);
        log.debug("bankCard = " + bankCard);
        log.debug("userName = " + userName);
        log.debug("openingBank = " + openingBank);
        log.debug("bBankProvince = " + bBankProvince);
        log.debug("bBankCity = " + bBankCity);
        log.debug("branchesBankId = " + branchesBankId);//用户可选

        if (StringUtils.isBlank(terminalTypeIdStr)) {
            log.warn("绑定银行卡号时, 传入参数terminalTypeId为空");
            sendWeChatErrorMsg("6001", "terminalTypeId");
            return null;
        }
        if (StringUtils.isBlank(bankCard)) {
            log.warn("绑定银行卡号时, 传入参数bankCard为空");
            sendWeChatErrorMsg("6001", "bankCard");
            return null;
        }
        if(BankCardTypeUtil.isCreditCard(bankCard)){
            log.warn("绑定银行卡时, 只能绑定储蓄卡!");
            sendWeChatErrorMsg("6122");
            return null;
        }
        if (StringUtils.isBlank(openingBank)) {
            log.warn("绑定银行卡号时, 传入参数openingBank为空");
            sendWeChatErrorMsg("6001", "openingBank");
            return null;
        }
        if (StringUtils.isBlank(userName)) {
            log.warn("绑定银行卡号时, 传入参数userName为空");
            sendWeChatErrorMsg("6001", "userName");
            return null;
        }
        if (null == bBankProvince) {
            log.warn("绑定银行卡号时, 传入参数bBankProvince为空");
            sendWeChatErrorMsg("6001", "bBankProvince");
            return null;
        }
        if (null == bBankCity) {
            log.warn("绑定银行卡号时, 传入参数bBankCity为空");
            sendWeChatErrorMsg("6001", "bBankCity");
            return null;
        }
        if (null == branchesBankId) {
            log.warn("绑定银行卡号时, 传入参数branchesBankId为空");
            sendWeChatErrorMsg("6001", "branchesBankId");
            return null;
        }
        if (null == identityCard) {
        	log.warn("绑定银行卡号时, 传入参数branchesBankId为空");
        	sendWeChatErrorMsg("6001", "identityCard");
        	return null;
        }
        terminalTypeId = Long.parseLong(terminalTypeIdStr);
        JSONObject result = new JSONObject();
        try {
            bankCard = bankCard.trim();
            userName = userName.trim();
            user = userService.getUserById(userId);
            user.setIdentityCard(identityCard);
            user.setUserName(userName);
            user.setCardholder(userName);
            user.setNickName(cusName);
            user.setBankCard(bankCard);
            user.setOpeningBank(openingBank);
            user.setBBankProvince(bBankProvince);
            user.setBBankCity(bBankCity);
            user.setClearMac(ClearMac.getUserClearMac(user.getLoginName(), user.getIdentityCard(), bankCard, openingBank, user.getCardholder()));//验证

            if (null != branchesBankId) {
                BankBranches bankB = bankBranchesService.searchBankBranchesById(branchesBankId);
                if (null != bankB) {
                    user.setBranchesBank(bankB.getName());
                    user.setBranchesBankCode(bankB.getCode());
                    user.setAccBankCode(ThreeMaoBankUtil.getCode(bankB.getBankId()));//三毛银行 代码
                } else {
                    log.debug("支行Id传入错误！");//userId.toString()
                    sendAppErrorMsg("9999");
                }
            }
            int flag = userService.bindingBankCard(user);

            if (flag > 0) {
                log.warn("绑定银行卡号成功！");
            	result.put("code", "0");
            	result.put("msg", "绑定银行卡号成功");
            	sendWeChatMsg(result.toString());
            } else {
            	result.put("code", "1");
            	result.put("msg", "绑定失败!");
                log.warn("绑定银行卡号失败！");
                sendWeChatMsg(result.toString());
            }
        } catch (Exception e) {
        	result.put("code", "1");
        	result.put("msg", "绑定失败!");
            log.warn("绑定银行卡号失败！");
            sendWeChatMsg(result.toString());
            e.printStackTrace();
        } finally {
            log.debug("--- bindingBankCard() end ---");
        }
    	return null;
    }

    /**
     * 微信公众号获取重置密码验证码
     * @return
     */
    public String mobileCodeSimple() throws Exception {
        String mobile = getRequest().getParameter("phoneNo");
        String phoneNoOptType = getRequest().getParameter("phoneNoOptType");
        String terminalTypeIdStr = getRequest().getParameter("terminalTypeId");

        if(StringUtils.isBlank(mobile)){
            log.debug("找回密码时,mobile参数为空!");
            sendWeChatErrorMsg("6001","mobile");
            return null;
        }

        if(StringUtils.isBlank(phoneNoOptType)){
            log.debug("找回密码时,phoneNoOptType参数为空!");
            sendWeChatErrorMsg("6001","phoneNoOptType");
            return null;
        }
        if(StringUtils.isBlank(terminalTypeIdStr)){
        	log.debug("找回密码时,terminalTypeId参数为空!");
        	sendWeChatErrorMsg("6001","terminalTypeId");
        	return null;
        }
        Long terminalTypeId = Long.parseLong(terminalTypeIdStr);
        User user = new User();
        user.setLoginName(mobile);
        user.setTerminalTypeId(terminalTypeId);
        user = userService.searchEntity(user);
        if(null == user){
            log.debug("找回密码时,用户未注册!");
            JSONObject json = new JSONObject();
            json.put("code","6001");
            json.put("msg","用户未注册!");
            sendWeChatMsg(json.toString());
            return null;
        }

        try {
            mobile = mobile.trim();
            JSONObject resultJson = new JSONObject();

            //获得手机注册验证码
            String code = NumberUtil.getRegisterMobileCode();

            SendmsgLog sendmsgLog = new SendmsgLog();
            sendmsgLog.setCode(code);
            sendmsgLog.setCreateDate(new Date());
            sendmsgLog.setCodeType(4);
            sendmsgLog.setMobile(mobile);
            sendmsgLog.setTerminalTypeId(terminalTypeId);
            sendmsgLog.setUserId(user.getId());

            if (sendmsgLogService.isSendOn60s(null, terminalTypeId, null)) {
                log.warn("发送手机验证码时, 一个手机在60秒内只能发送一条信息");
                sendmsgLog.setStatus(3);//未发送
                sendmsgLog.setReqCode("6103");
                sendmsgLog.setReqMsg("一个手机在60秒内只能发送一条信息！");
                sendmsgLogService.insertEntity(sendmsgLog);
                sendWeChatErrorMsg("6103");
                return null;
            }
            if (sendmsgLogService.isExceed30(null, terminalTypeId, null)) {
                log.warn("发送手机验证码时, 一个手机一天内最多发送30条验证信息");
                sendmsgLog.setStatus(3);//未发送
                sendmsgLog.setReqCode("6104");
                sendmsgLog.setReqMsg("一个手机一天内最多发送30条验证信息！");
                sendmsgLogService.insertEntity(sendmsgLog);
                sendWeChatErrorMsg("6104");
                return null;
            }
            String content = "尊敬的客户您好,您的手机验证码为: [" + code + "],感谢您的支持！";
            resultJson = JSONObject.fromObject(verifiService.sendMobileCode(mobile, code, sendmsgLog, content));
            resultJson.put("code","0");
            sendWeChatMsg(resultJson.toString());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            log.debug("--- register() end ---");
        }
        return null;
    }

    /**
     * 重置微信公众号用户密码
     * @return
     */
    public String customerResetPswd() throws Exception {
        String mobile = getRequest().getParameter("phoneNo");
        String password = getRequest().getParameter("password");
        if (StringUtils.isBlank(password)) {
            log.warn("重置密码时, 传入参数mobile为空");
            sendWeChatErrorMsg("6001", "mobile");
            return null;
        }
        if (StringUtils.isBlank(password)) {
            log.warn("重置密码时, 传入参数password为空");
            sendWeChatErrorMsg("6001", "password");
            return null;
        }
        if (StringUtils.isBlank(getRequest().getParameter("terminalTypeId"))) {
        	log.warn("重置密码时, 传入参数terminalTypeId为空");
        	sendWeChatErrorMsg("6001", "terminalTypeId");
        	return null;
        }
        Long terminalTypeId = Long.parseLong(getRequest().getParameter("terminalTypeId"));
        User user = new User();
        user.setTerminalTypeId(terminalTypeId);
        user.setLoginName(mobile);
        user.setDeleted(0);
        user = userService.searchEntity(user);
        password = MD5.mD5ofStr(password);
        user.setPassword(password);
        int status = userService.updateEntity(user);
        JSONObject result = new JSONObject();
        if(status == 1){
            result.put("code", "0");
            result.put("msg", "密码重置成功!");
        }else{
            result.put("code", "1");
            result.put("msg", "密码重置失败!");
        }
        sendWeChatMsg(result.toString());
        return null;
    }

    /**
     * 公众号商户登录
     * @return
     */
    public String customerRegisterManage(){
    	String terminalTypeId = getRequest().getParameter("terminalTypeId");
    	if(StringUtils.isBlank(terminalTypeId)){
            log.debug("公众号商户登录时,terminalTypeId参数为空!");
            sendWeChatErrorMsg("6001","terminalTypeId");
            return null;
        }
    	getRequest().setAttribute("terminalTypeId", terminalTypeId);
        return "login_"+terminalTypeId;
    }

    /**
     * 微信公众号用户登录
     *
     * @return
     * @throws Exception
     */
    public String customerLogin() throws Exception {
        log.debug("--- customerLogin() start ---");

        String phoneNo = getRequest().getParameter("phoneNo");
        String password = getRequest().getParameter("password");
        String terminalTypeIdStr = getRequest().getParameter("terminalTypeId");

        log.debug("phoneNo = " + phoneNo);
        log.debug("password = " + password);

        if (StringUtils.isBlank(phoneNo)){
            log.warn("用户登录时, 传入参数phoneNo为空");
            sendWeChatErrorMsg("6001", "phoneNo");
            return null;
        }
        if (StringUtils.isBlank(password)){
            log.warn("用户登录时, 传入参数password为空");
            sendWeChatErrorMsg("6001", "password");
            return null;
        }
        if (StringUtils.isBlank(terminalTypeIdStr)){
        	log.warn("用户登录时, 传入参数terminalTypeId为空");
        	sendWeChatErrorMsg("6001", "terminalTypeId");
        	return null;
        }
        if (!RegularUtils.checkMobile(phoneNo)) {
            log.warn("用户登录时, 手机号格式错误");
            sendWeChatErrorMsg("6102");
            return null;
        }

        try {
        	Long terminalTypeId = Long.parseLong(terminalTypeIdStr);
            phoneNo = phoneNo.trim();
            user = new User();
            user.setMobile(phoneNo);
            user.setTerminalTypeId(terminalTypeId);
            user = userService.searchEntity(user);

            if (null != user) {
                if (null != terminalTypeId && (null == user.getTerminalTypeId() || !user.getTerminalTypeId().equals(terminalTypeId))) {//不是一个终端 提示为用户不存在
                    log.warn("登录时，用户名不存在！");//不是一个终端
                    sendWeChatErrorMsg("6008");
                    return null;
                }

                user.setMobile(mobile);
                password = MD5.mD5ofStr(password);
                user.setPassword(password);
                user = userService.searchEntity(user);

                if (null != user) {
                    if (1 == user.getDeleted().intValue()) {
                        log.warn("登录时，该用户已暂停使用！");
                        sendWeChatErrorMsg("6004");
                        return null;
                    } else if (2 == user.getDeleted().intValue()) {
                        log.warn("登录时，该用户已被注销！");
                        sendWeChatErrorMsg("6005");
                        return null;
                    }

                    JSONObject result = new JSONObject();
                    result.put("code", "0");
                    result.put("cusNo", user.getMobile());
                    result.put("cusId", user.getActivationCode());
                    result.put("settleAccNo", modifyBankCard(null != user.getBankCard() ? user.getBankCard() : ""));
                    result.put("cusName", user.getNickName());
                    result.put("cusStatus","TRUE");
                    result.put("loanProvince",user.getbBankProvince());
                    result.put("loanCity",user.getbBankCity());
                    result.put("loanUserName",user.getUserName());
                    result.put("userId",user.getId());

                    //实名认证错误信息
                    result.put("dPIStatus", (null == user.getDPIStatus() || 4 == user.getDPIStatus().intValue()) ? 3 : user.getDPIStatus());//4重置暂时改为3
                    if ((null == user.getUserName() || user.getUserName().indexOf("null") != -1) && !(null == user.getDPIStatus() || 3 == user.getDPIStatus().intValue()))//如果用户名为空 那么实名认证不通过
                        result.put("cusStatus", "FALSE");
                    if(user.getDPIStatus() == 1){
                        result.put("cusStatus", "TRUE");
                    }else if(user.getDPIStatus() == 2){
                        result.put("cusStatus", "AUDITING");
                    }else{
                        result.put("cusStatus", "FALSE");
                    }

                    log.debug(" 用户 " + user.getMobile() + " 登录成功！");
                    result.put("msg", "用户登录成功！");

                    if (null != user.getDPIStatus() && 0 == user.getDPIStatus().intValue()) {
                        //查询最后 认证失败的认证信息
                        UserDPI userDPI = userDPIService.searchLatestUserDPIError(terminalTypeId, roleId, user.getId());
                        result.put("msg", null == userDPI ? "亲，您上传的身份证图片有点模糊，请重新上传！" : userDPI.getDescription());
                    }
                    if (null != user.getDPIStatus() && 3 == user.getDPIStatus().intValue()) {
                        //查询最后 认证失败的认证信息
                        result.put("msg", "亲,您尚未进行实名认证或实名认证未完成,请您重新实名认证!");
                    }

                    DecimalFormat df = new DecimalFormat("######0.00");
                    UserMoney userMoney = new UserMoney();
                    userMoney.setUserId(user.getUserId());
                    userMoney = userMoneyService.searchEntity(userMoney);
                    if(userMoney != null){
                        result.put("userMoney",df.format(userMoney.getMoney()));
                    }else {
                        result.put("userMoney",df.format("0.00"));
                    }

                    sendWeChatMsg(result.toString());

                    //将用户登录信息保存到 session 中
                    userService.saveMemcachedByUser(user);
                    getSession().setAttribute(SESSION_USER, user);

                } else {
                    log.warn("登录时，密码错误！");
                    sendWeChatErrorMsg("6006");
                }
            } else {
                log.warn("登录时，用户名不存在！");
                sendWeChatErrorMsg("6008");
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            log.debug("--- customerLogin() end ---");
        }
    }
    /**
     * 微信支付成功页面
     * @return
     * @throws IOException
     */
    public String weixinPaySuccess() throws IOException{

    	//{"organizationId":"slcceshi4","merName":"固定码支付测试","sendTime":"20160929183719","transAmt":"10","orgSendSeqId":"183719039","payResult":"00","payDesc":"支付成功"}
		String data = getRequest().getParameter("data");
		log.info("接收到商联储交易结果通知：{}",data);
		String amt = "";
		//显示订单号
    	String orderId = "";
    	String payDesc = "支付成功";
		if(StringUtils.isNotBlank(data)){
			Map<String, String> resultMap = JSONUtil.parseToBean(data);
			orderId = resultMap.get("orgSendSeqId");
			String transAmt = resultMap.get("transAmt");
			payDesc = resultMap.get("payDesc");
			double parseInt = Double.parseDouble(transAmt)/100;
			amt = String.valueOf(parseInt);
		}else{
			 amt = getRequest().getParameter("amt");
			 orderId = getRequest().getParameter("orderId");
		}

    	getRequest().setAttribute("amt", amt);
    	getRequest().setAttribute("orderId", orderId);
    	getRequest().setAttribute("payDesc", payDesc);
    	getRequest().setAttribute("time", DateUtils.dateParseString(new Date()));

    	//金额
        return "weixinPaySuccess";
    }

    /**
     * 跳转贷款页面
     * @return
     * @throws Exception
     */
    public String customerLoan() throws Exception{
        String terminalTypeId = getRequest().getParameter("terminalTypeId");
        getRequest().setAttribute("terminalTypeId",terminalTypeId);
        return "customerLoan";
    }

    /**
     * 提交贷款信息
     * @return
     */
    public String customerLoans() throws Exception{
        String job = getRequest().getParameter("job");
        String customerName = getRequest().getParameter("customerName");
        String cusSettleProvince = getRequest().getParameter("cusSettleProvince");
        String cusSettleCity = getRequest().getParameter("cusSettleCity");
        String amount = getRequest().getParameter("amount");
        String loanDate = getRequest().getParameter("loanDate");
        String phone = getRequest().getParameter("phone");
        String jobType = getRequest().getParameter("jobType");
        String jobYears = getRequest().getParameter("jobYears");
        String salary = getRequest().getParameter("salary");
        String sellYears = getRequest().getParameter("sellYears");
        String yearSalary = getRequest().getParameter("yearSalary");
        String houseSum = getRequest().getParameter("houseSum");
        String shopName = getRequest().getParameter("shopName");
        String platform = getRequest().getParameter("platform");
        String sucSum = getRequest().getParameter("sucSum");
        String userId = getRequest().getParameter("userId");

        loan = new Loan();
        loan.setId(Identities.uuid2());
        loan.setJob(job);
        loan.setCustomerName(customerName);
        loan.setCusSettleProvince(cusSettleProvince);
        loan.setCusSettleCity(cusSettleCity);
        loan.setAmount(Integer.parseInt(amount));
        loan.setLoanDate(loanDate);
        loan.setPhone(phone);
        loan.setStatus(1);
        loan.setCreateDate(new Date());
        loan.setJobType(jobType);
        loan.setJobYears(jobYears);
        loan.setUserId(Long.parseLong(userId));
        if( salary != null ){
            loan.setSalary(Integer.parseInt(salary));
        }
        loan.setSellYears(sellYears);
        if( yearSalary != null){
            loan.setYearSalary(Integer.parseInt(yearSalary));
        }
        loan.setHouseSum(houseSum);
        loan.setShopName(shopName);
        loan.setPlatform(platform);
        if( sucSum != null ){
            loan.setSucSum(Integer.parseInt(sucSum));
        }
        loanService.insert(loan);
        JSONObject result = new JSONObject();
        result.put("code", "0");
        sendWeChatMsg(result.toString());
        return null;
    }

}